发布表单请求对象是“对象对象”

Kay*_*ote 3 javascript ajax request node.js express

刚刚进入 Node & 我在这里阅读了一些关于此的问题,但是,请求正文仍然是 { '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'));
Run Code Online (Sandbox Code Playgroud)

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

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));
};
Run Code Online (Sandbox Code Playgroud)

r.d*_*lic 6

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

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

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