客户端的发布方法对服务器节点做出反应

时间:2018-06-29 07:08:42

标签: node.js reactjs express

我正在将react(frontEnd)与nodejs(后端)一起使用,我正尝试将来自客户端的发布请求发送到服务器。

客户端

在下面,我使用斧头将请求发送到服务器。 我试着在没有轴心的情况下直接调用fetch。我对添加localhost:5000感到厌倦,但没有添加,但是我仍然无法正常工作。

仅供参考,我正在发送的所有数据均有效,并且已按要求提供。 enter image description here

服务器

在这里,我正在尝试处理我的请求,至少将其打印到控制台以验证我的请求是否有效传递

enter image description here

打印结果!

enter image description here

关于上述内容,您能提供建议吗?

添加正文解析器后:   当前我正在获取一个未定义的对象,请您指教吗? enter image description here

3 个答案:

答案 0 :(得分:0)

您不需要从react axios请求中JSON.stringify来获取数据。

这是一个例子:

const user = {
    name: this.state.name
};

axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
    .then(res => {
        console.log(res);
        console.log(res.data);
    }
)

有关更多信息,请阅读Using Axios with React

答案 1 :(得分:0)

在标题中设置内容类型并检查

axios.post('url', data, {
    headers: {
        'Content-Type': 'application/json',
    }
}

答案 2 :(得分:0)

尝试这种方式

const data = {
    name: this.state.additionalCost
};

 axios
      .post(
        '/api/processData',
        data,
        { headers: { 'Content-Type': 'application/json' } }
      )
      .then(function(result) {
       console.log(result);
      });

并在Express应用中使用body-parser

import express from 'express';
import bodyParser from 'body-parser';

app.use(bodyParser.json());