如何从React前端向节点后端发出发布请求?得到404

时间:2019-07-13 16:46:57

标签: javascript node.js reactjs mern react-fullstack

我正在尝试建立一个简单的网站,用户可以在其中发布东西以学习MEAN堆栈。当我处理POST请求时,该请求将被处理并通过后端输入到MongoDB服务器。 React在端口3000上,服务器在5000上。如何使请求从3000变为5000?我的请求通过Postman运行,但不使用axios。我将代理添加到客户端package.json。

我尝试过更改代理,添加CORS,更改为每条可能的路线。什么都没有。

后端:

router.post('/api/req',(req,res)=>{
    const newPost = new Post({
        title: req.body.title,
        description: req.body.description
    })
    newPost.save().then(()=>{
        console.log('Item added to database!')
    });

})

前端:

axios({
      method: 'post',
      url: '/api/req',
      data: {
        title: this.state.title
      },
      validateStatus: (status) => {
        return true; 
      },
    }).catch(error => {
        console.log(error);
    }).then(response => {
        console.log(response);
    });

“代理”:“ http://localhost:5000/”-package.json

我希望POST请求能够通过,并且标题将输入到数据库中。相反,我收到错误消息:无法加载资源:服务器以状态404(未找到)进行了响应

该错误来自本地主机:3000 / api / req,它应该是代理端口5000。而且,实际路由是route / api / req.js。

1 个答案:

答案 0 :(得分:0)

您将必须传递完整的网址:

axios({
      method: 'post',
      url: 'http://example.com:5000/api/req',
      data: {
        title: this.state.title
      },
      validateStatus: (status) => {
        return true; 
      },
    }).catch(error => {
        console.log(error);
    }).then(response => {
        console.log(response);
    });