【问题标题】:Receiving net::ERR_EMPTY_RESPONSE with Nodejs Post Request使用 Nodejs 发布请求接收 net::ERR_EMPTY_RESPONSE
【发布时间】:2017-04-23 18:59:56
【问题描述】:

我正在尝试在我的 Node 应用程序中发出发布请求;但是,我收到以下错误。

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;

由于我在 onclick 调用我的 ejs 文件中的函数后调用此路由,因此这是我的 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

【问题讨论】:

  • 您解决了这个问题吗?自从我遇到这个问题以来已经有 2 周了,我尝试过的所有方法都不起作用......谢谢!

标签: javascript node.js ajax express post


【解决方案1】:

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

然后检查您的 URL,您使用某个名称注册了您的模块,因此您的 URL 应该看起来像 /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')`

【讨论】:

  • 啊,不幸的是没有运气:/知道为什么吗?
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2018-08-14
  • 1970-01-01
相关资源
最近更新 更多