【问题标题】:React + Expressjs URL params returning undefined on get requestReact + Expressjs URL 参数在获取请求时返回未定义
【发布时间】:2021-02-09 21:41:41
【问题描述】:

所以我正在尝试制作一个存储用户的 Web 应用程序。我想在后端使用这个用户来检索信息。所以现在点击了一个按钮并调用了后端,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 函数从前端单击按钮时,控制台和浏览器会将用户记录为 "undefined"。但是,当我将链接放在 浏览器上直接为: http://localhost:4000/prize?username=test3%40something.edu 我成功获得 “test3@something.edu” 工作。我怎样才能让按钮给我和放在浏览器上一样?

谢谢。

【问题讨论】:

  • 显示您“记录用户”的方式。 fetch 返回一个承诺。

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


【解决方案1】:

我认为您不小心在网址中添加了 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,
    });
}

【讨论】:

    猜你喜欢
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2018-08-09
    • 2022-01-16
    相关资源
    最近更新 更多