0

我正在尝试制作一个简单的网站,用户可以在其中发布内容以学习 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(未找到)

错误来自 localhost:3000/api/req,它应该是代理端口 5000。另外,实际路由是 routes/api/req.js。

4

1 回答 1

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);
    });
于 2019-07-13T16:51:52.197 回答