node.js - 无法读取 Node 中获取的帖子

标签 node.js reactjs redux fetch-api

我正在将数据 {id: "abc123", text: "sometext"} 发布到 Node API。通过 action 调用从组件发布:

export function addTextToAPI(inputData) {
    return(dispatch) => {
        console.log(inputData),
        dispatch(addText(inputData))
         fetch(myapi, { 
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
            method: 'POST',
            data:  inputData
      })
        .then(res => res.json())
    }
}

console.log(inputData) 为 {id: "abc123", text: "sometext"}

Node :

var express    = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/addtest', (req, res) => {

    console.log(req.body);        // <= returns blank object {}

    console.log(req.body.data);   // <= returns undefined

    console.log(req.query);       // <= returns blank object {}

    console.log("test added");      

});


app.listen(3000);

我希望能够读取 req 中的 inputData。我怎么做?我希望能够读取 req 中的 inputData。我该怎么做?

最佳答案

要发布数据,您需要传入 body 参数来获取。

这应该有效:

export function addTextToAPI(inputData) {
    return(dispatch) => {
        console.log(inputData),
        dispatch(addText(inputData))
         fetch(myapi, { 
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
            method: 'POST',
            body: JSON.stringify(inputData)
      })
        .then(res => res.json())
    }
}

关于node.js - 无法读取 Node 中获取的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248545/

相关文章:

javascript - Action 分派(dispatch)后渲染组件

node.js - 如何检查 xero 中联系人的帐号字段是否重复?

javascript - Express/Mongoose 项目中的 HTTP Get 和 Post 请求中缺少内容

node.js - 为什么每个人都使用 Node.js 和 NPM 来编译 JavaScript 库?

javascript - 在 React 应用程序中切换到 TypeScript 的问题

javascript - Material -UI FAB 悬停颜色

mysql - Node JS mysql 用大查询更新

javascript - 在 React 中单击元素时修改类名

reactjs - React + Redux 作为静态站点 : limitations?

redux - redux mapStateToProps 的最佳实践?