2017-04-22 205 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