【问题标题】:How to access data from API Payload如何从 API 负载访问数据
【发布时间】:2023-02-23 23:50:42
【问题描述】:

我正在像这样进行 api 调用
axios.get("http://localhost:4000/loginUser", { 邮箱: enteredEmail, 密码: enteredPass})
现在我想在服务器代码中访问这些提供给 API 调用的电子邮件和密码字段,

app.get("/loginUser", async (req, res) => {
   try {
        email = // don't know how to access this email field from **req**
   } catch (error) {
         res.status(400).send("invalid credentials");
   }
});

我尝试从 res.body 访问它,但它是空的,因为我将数据作为有效负载传递。并尝试作为参数传递,但电子邮件中的 @ 符号出现问题。

【问题讨论】:

    标签: javascript node.js api server


    【解决方案1】:

    来自the documentation

    axios.get(url[, config])
    

    get 的第二个参数是配置不是请求体。

    GET 请求不能有正文。

    如果你想在 GET 请求中对数据进行编码,你可以在 URL (不要对密码这样做).

    const url = new URL("http://localhost:4000/loginUser");
    url.searchParams.set("email", enteredEmail);
    url.searchParams.set("password", enteredPass);
    axios.get(url);
    

    可以通过 the query property 在 Express 中访问它。


    如果你想传递凭据不要使用网址. Web 服务器倾向于以明文形式记录请求的 URL。

    改为发出 POST 请求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多