Home  >  Q&A  >  body text

node.js - nodejs post 传值方式

第一种方式:
前端

 $.ajaxSetup({
    contentType: "application/json; charset=utf-8"
  }); 

  $.post('/test', JSON.stringify({
      "Email": "sfpe@163.com",
      "Password": "123456",
      "person": {
        "age": 25
      }
    }), function(data){
    debugger
  }); 

后端

console.log(util.inspect({a: req.body}));
console.log(util.inspect({a: req.body.Email})); 

结果

{ a:
   { Email: 'sfpe@163.com',
     Password: '123456',
     person: { age: 25 } } }
{ a: 'sfpe@163.com' }

第二种方式
前端

$.post('/test', {
    post:JSON.stringify({
      "Email": "sfpe@163.com",
      "Password": "123456",
      "person": {
        "age": 25
      }
    })
  }, function(data){
    debugger
  });  

后端

console.log(util.inspect({a: req.body.post}));
console.log(util.inspect({a: req.body.post.Email}));

结果

{ a: '{"Email":"sfpe@163.com","Password":"123456","person":   {"age":25}}' }
{ a: undefined }       

问题:哪种传给后端的是json格式 ? 我用第二种传了,后端说不是json的格式....用第一种,报了这种错误: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我现在都不知道是我的问题 还是后端的问题。

天蓬老师天蓬老师2713 days ago898

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:02:37

    Cross-domain request processing

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:02:37

    The first one is OK, but it is cross-domain. You can look at building public APIs and CORS

    Let me briefly explain why the console reported an error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

    is because, in the POST method, the header in content-type is not any of application/x-www-form-urlencoded,multipart/form-data, multipart/form-data, and text/plain. What you set is application/json; charset=utf-8, which means that this request is a "complex" request. Then when the complex request faces cross-domain access, the backend service will be requested to provide corresponding support. For details, please refer to the document I posted, which contains the chapter "Not That Simple Request". It's best to take your back-end colleagues to read it together, lest they don't support you and you have to do it yourself for a long time. It’s useless

    reply
    0
  • Cancelreply