weixin_33726943
2020-03-31 07:30
采纳率: 0%
浏览 1.2k

为什么REQ.BODY始终为空?

I know there are a lot of answer already marked as a working solution, but I can't make it work in my case, so please don't marked it as already answered, this is my scenario:

AJAX CLIENT SIDE

var data ={};
data.test="ciaozio";
$.ajax({
    url: 'http://localhost:5000/dir',
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data),
    header: "Access-Control-Allow-Origin",
    success: function(data){
        console.log(data);
    },
    error: function(data) {
        console.log("error");
    }
});

NODEJS SERVER-SIDE

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(bodyParser.json()); // support json encoded bodies
app.use('/', router);

app.post('/dir', function (req, res) {
  console.log(req.body);
  res.end("Ok");
})

var server = app.listen(5000, function () {
   var host = server.address().address
   var port = server.address().port
   console.log("Example app listening at http://%s:%s", host, port)
})

CONSOLE-OUTPUT

Example app listening at http://:::5000
{}

CLIENT-SIDE CONSOLE OUTPUT

Access to XMLHttpRequest at 'http://localhost:5000/dir' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.js:29 error
jquery-3.4.1.min.js:2 POST http://localhost:5000/dir net::ERR_FAILED

图片转代码服务由CSDN问答提供 功能建议

                    

我知道有很多答案已经被标记为有效的解决方案,但是对于我而言,我无法使其正常工作,因此请不要将其标记为已解决,这是我的情况:

AJAX客户端

  var data = {};
 data.test =“ ciaozio”;
 $ .ajax({
     网址:“ http:// localhost:5000 / dir”,
     方法:“ POST”,
     contentType:“ application / json”,
     数据:JSON.stringify(data),
     标头:“ Access-Control-Allow-Origin”,
     成功:功能(数据){
         console.log(data);
     },
     错误:函数(数据){
         console.log(“错误”);
     }
 });
  

 

NODEJS服务器端

  var express = require('express');
 var bodyParser = require('body-parser');
 var app = express();
 var router = express.Router();
 app.use(bodyParser.urlencoded({extended:true}));  //支持编码的主体
 app.use(bodyParser.json());  //支持json编码的主体
 app.use('/',路由器);

 app.post('/ dir',函数(req,res){
   console.log(要求正文);
   res.end(“确定”);
 })

 var server = app.listen(5000,function(){
    var host = server.address()。address
    var port = server.address()。port
    console.log(“示例应用程序在http://%s:%s上监听”,主机,端口)
 })
  

 

控制台输出

 示例应用程序在http:// ::: 5000上监听
 {}
  

 

客户端控制台输出

 从原点'null'对'http:// localhost:5000 / dir'处的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control  -Allow-Origin'标头出现在请求的资源上。
 index.js:29错误
 jquery-3.4.1.min.js:2 POST http:// localhost:5000 / dir net :: ERR_FAILED
  
     
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题