2017-04-22 201 views
0

我想在我的节点应用程序中发布发布请求;但是,我收到以下错误。接收网:: ERR_EMPTY_RESPONSE与Nodejs发布请求

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE 

如何解决这个问题?

这里是我的路线:

var express = require('express'); 
var router = express.Router(); 
var Debate = require('../models/debate'); 
var mdb = require('mongodb').MongoClient, 
    ObjectId = require('mongodb').ObjectID, 
    assert = require('assert'); 
var api_version = '1'; 
var url = 'mongodb://localhost:27017/debate'; 

router.post('/'+api_version+'/postDebate', function(req, res, next) { 
    var debate = new Debate(req.body); 
    console.log(debate, "here is the debate"); 
    debate.save(function(err) { 
    if (err) throw err; 
    console.log('Debate saved successfully!'); 
    }); 
    res.json(debate); 
}); 

module.exports = router; 

而且因为我在后我EJS文件的onclick调用一个函数,调用这里这条路线是我的JavaScript文件。

function postDebate() { 
    var topic = document.getElementById('topic').value; 
    var tags = document.getElementById('tags').value; 
    var argument = document.getElementById('argument').value; 

    var debateObject = { 
    "topic": topic, 
    "tags": tags, 
    "argument": argument 
    }; 
    console.log(topic, tags, argument); 

    $.ajax({ 
    type: 'POST', 
    data: JSON.stringify(debateObject), 
    contentType: "application/json", 
     //contentType: "application/x-www-form-urlencoded", 
     dataType:'json', 
     url: 'http://localhost:27017/post',      
     success: function(data) { 
      console.log(JSON.stringify(data), "This is the debateObject");        
     }, 
     error: function(error) { 
      console.log(error); 
     } 
     }); 
} 

如何解决此错误?这里有什么问题?

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE 
+0

你是否设法解决这个问题?有2个星期,因为我有这个问题,我所尝试的一切都不工作......谢谢! – Valip

回答

0

您需要在app级别添加CORS标头,你必须运行res.end()在OPTIONS请求

然后检查你的网址,您注册的模块的一些名称,以便您的网址应看起来像/ROUTER_MODULE_NAME/1/postDebate但是从你的前端,你打电话给http://localhost:27017/post

这里是我查小例子,它为我工作得很好:

var express = require('express'); 
var router = express.Router(); 
var app = express(); 

app.use(function(req, res, next) { 
    console.log('request', req.url, req.body, req.method); 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-token"); 
    if(req.method === 'OPTIONS') { 
     res.end(); 
    } 
    else { 
     next(); 
    } 
}); 

router.get('/hello', function(req, res, next) { 
    res.end('hello world') 
}); 

app.use('/router', router) 

app.listen(8081) 

//try in browser `$.get('http://127.0.0.1:8081/router/hello')` 
+0

不幸的是没有运气:/任何想法为什么? –

+0

检查编辑的答案,应该工作 – h0x91B