React + Expressjs URL 参数在获取请求时返回未定义

React + Expressjs URL params returning undefined on get request

所以我正在尝试制作一个存储用户的网络应用程序。我想在后端使用这个用户来检索信息。所以现在点击一个按钮并调用后端,onClick 函数目前看起来像这样。

const getBackend = () => {
    let url = new URL('https://http://localhost:4000/backend');
    url.search = new URLSearchParams({
        username: user,
    });
    fetch(`http://localhost:4000/prize`, {
        method: "GET",
        url:url,
    });
}

我的 express.js 服务器看起来像这样:

app.get("/backend", async (req, res) => {
    let user = req.query.username;
    console.log("user");
    res.send(user);
}

当我使用 getBackend 函数从前端单击按钮时,控制台和浏览器将记录用户作为 “未定义”。但是,当我将 link 直接放在 浏览器上时 为: http://localhost:4000/prize?username=test3%40something.edu 我成功地让 "test3@something.edu" 工作。怎样才能让按钮给我的和放在浏览器上一样?

谢谢。

我认为您不小心在 url 中添加了 https。你应该离开 https,只保留 http

const getBackend = () => {
    let url = new URL('http://localhost:4000/backend');
    url.search = new URLSearchParams({
        username: user,
    });
    fetch(`http://localhost:4000/prize`, {
        method: "GET",
        url:url,
    });
}