【问题标题】:ExpressJs | req.body is not empty, but can't acces data快递 Js | req.body 不为空,但不能访问数据
【发布时间】:2017-08-26 08:48:37
【问题描述】:

我正在将一些数据从我的 ReactJS 客户端发布到 Express 服务器,但似乎我无法访问 req.body 中的数据...。我正在以这种方式发送 JSON 对象:

var url = 'http://localhost:8000/scrape/';
    const {main} = getState()

    const info = { name : main.title, items : main.list}
    var options = {
      url: url,
      method: 'POST',
      body : JSON.stringify(info),
      json: true,
      headers : {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };


    Request(options, (error, response, data) => {
        // !error ? dispatch( setSearchResults(JSON.parse(data) ) ) : dispatch( setError(error) );
    });

当我在 Express 中使用 console.log(req.body) 时,我收到:

{ '{"name":"test","items":': { '{"url":"test","code":"ING"},{"url":"test","code":"KIN"},{"url":"test","code":"GAO"}': '' } }

在我的 Express 中,我使用 bodyParser

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

我尝试使用 JSON.stringify(req.body) 和 JSON.parse(req.body) 但都没有成功,有什么建议吗?

【问题讨论】:

  • 为什么将Content-Type 设为application/x-www-form-urlencoded 而POST 正文是JSON?
  • 是的,我注意到当我查看代码时,似乎当我尝试 application/json 时,req.body 将在 Express 中保持为空
  • 代码中的Request模块是什么?另外,您是否检查过浏览器开发工具中的 HTTP 网络——当Content-Typeapplication/json 时,客户端发送的 JSON 正文是?
  • Request is this libary npmjs.com/package/request ,当 Content-Type 为 application/json 时,请求将作为 OPTIONS 请求发送,甚至不会到达我的快递服务器
  • 正文解析器不链接,每个请求只能运行一个。在这种情况下,似乎urlencoded 开始并解析了作为字符串的主体,所以我猜req.body 是一个字符串。底线:使用 JSON 内容类型

标签: json node.js express


【解决方案1】:

这是解决方案: How to allow CORS?

这就是我提出正确 JSON 请求的方式:

var options = {
      uri: url,
      method: 'POST',
      json: {
        "name": main.tile, "items" : main.list
      }
    };

    Request(options, (error, response, data) => {

    });

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2021-04-14
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多