首页 > 解决方案 > 如何使用 fetch 和 request react js 更改端口?

问题描述

这是我从教授的教程中获取的代码。LoginComp 只是 {用户名:'',密码:''}

const request = new Request("/users/login", {
    method: "post",
    body: JSON.stringify(loginComp),
    headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json"
    }
});

// Send the request with fetch()
fetch(request)
    .then(res => {
        if (res.status === 200) {
            return res.json()


        }
    })

    .catch(error => {
        console.log(error);
    });

我有一个在 localhost:5000 运行的后端服务器,在 localhost:5000/users/login 有发布路由。这段代码的问题是它假设用户/登录是在 localhost 3000 所以我会在控制台中得到这个错误:

POST http://localhost:3000/users/login 404 (Not Found)

我如何使它成为 localhost:5000 而不是 3000 (客户端服务器)

标签: node.jsreactjsexpressfetch

解决方案


您必须将 http://localhost:5000/ 添加到您的网址。

const request = new Request("http://localhost:5000/users/login", {
    method: "post",
    body: JSON.stringify(loginComp),
    headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json"
    }
});

推荐阅读