代理无法将请求从一个端口发送到另一个端口

Proxy not working for sending requests from one port to another

我在学习课程的同时尝试使用 MERN 堆栈构建一个简单的 Web 应用程序。

我的后端在端口 5000 上运行,而反应在端口 3000 上运行。当我想向后端发出请求时 API,它将它发送到端口 3000 而不是 5000。我不断收到此错误留言:

xhr.js:178 POST http://localhost:3000/api/users 400 (Bad Request)

我在 package.json 中加入了 "proxy" : "http://localhost:5000"。我尝试用 127.0.0.1 替换 'localhost'。我尝试删除并重新安装 package-lock.json 和 node_modules 文件夹。我尝试删除代理并使用整个 url。我尝试安装 http 代理中间件。我也尝试在后端启用 CORS。

要么我被诅咒了,要么我做错了。

我正在使用 axios 处理请求,这是代码。

const config = {
     headers: {
         'Content-type': "application-json"
     }
}

const body = JSON.stringify(newUser)
const res = await axios.post('/api/users', body, config)
console.log(res.data)

尝试将基础 url 添加到 axios 配置中:

const config = {
    headers: {
        'Content-type': "application-json"
    }
    baseURL: 'http://localhost:5000',
}

绝对不是代理问题。问题可能是您将正文作为 JSON 字符串传递给 axios post() 方法。不需要这样做,只需传递对象:

const res = await axios.post('/api/users', newUser, config)

此外,Content-type 的正确值是 application/json(不是 application-json