发布表单请求对象是'对象对象'

时间:2018-03-23 17:48:42

标签: javascript node.js ajax express request

刚进入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'));

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

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));
};

1 个答案:

答案 0 :(得分:2)

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

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

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