【问题标题】:Post Form Request Object Is 'object Object'发布表单请求对象是“对象对象”
【发布时间】:2018-09-02 11:36:07
【问题描述】:

刚刚进入 Node,我已经阅读了一些关于 SO 的问题,但是,请求正文仍然是 { 'object Object' : ''}

服务器代码是:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

app.get('/', (req, res) => {
  res.send('this is a normal response');
});

app.post('/d*', (req, res) => {
  const reqBody = req.body;
  console.log(req.body);  // console => {`object Object` : ''} 
  res.send(reqBody);
});
app.listen(app.get('port'), () => console.log('Server instance running on http://localhost:1111'));

客户端函数是一个简单的“获取请求”:

const postRegistrationForm = (userDetails, dispatch) => {
  const url = 'http://localhost:1111/d/register';
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: userDetails
  };
  fetch(url, config)
    .then(data => data.json())
    .then(res => console.log('rezzz is...', res));
};

【问题讨论】:

  • 试试console.log(JSON.stringify(req.body))

标签: javascript node.js ajax express request


【解决方案1】:

在使用 fetch 发送之前,您需要对任何主体/对象进行字符串化。

尝试使用此配置进行抓取:

const config = {
    method: 'POST',
    headers: {
        'Accept': 'application/json'
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(userDetails)
 };

【讨论】:

  • 确实做到了。我需要将对象字符串化为 POST。谢谢。
猜你喜欢
  • 2015-09-27
  • 2014-12-08
  • 2021-02-26
  • 2018-10-24
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多