繁体   English   中英

从前端传递参数以在后端使用

[英]Passing parameters from frontend to be used in backend

我有一个前端 (html) 和 Node.js 后端 (express)。 我想向第三方 api 提出请求,但有 cors 问题。

现在我希望能够根据前端的请求(例如localbackend:3000/${input_value} )将输入的值和 append 抓取到我的后端 url ,然后在我的后端使用传递的参数( input_value )来形成api url 我需要拨打外部api。

一些代码:

index.html

<input type="text" id="text">

索引.js

document.getElementById("send").addEventListener("click", async (e) => {
  e.preventDefault();

  var message = document.getElementById("text").value;

  if (message == undefined || message == "") {
  } else {
    let response = "";

    await fetch(`http://localhost:3000/${message}`)
      .then((data) => data.json())
      .then((data) => response = data)
      .catch((error) => console.error(error));

.... then response to be appended to another div... 

服务器.js

app.get("/", (req, res) => {
axios
    .request(
      `http://someexternalserver/get?uid="simon"&msg=${where_i_need_the_input}` 
    )
    .then(function (response) {
      res.send(JSON.stringify(response.data));  
    })
    .catch(function (error) {
      console.error(error);
    });
});

手动我能够成功测试外部 api 但我希望动态完成。

随意分享更好的解决方案或简单地分享如何让它工作。 请不要使用 FE 框架。

我试过了:

Rob 的 cors-anywhere ( https://cors-anywhere.herokuapp.com/ ) 代理已被 api 限制。

似乎有些不对劲。 您的前端应用程序似乎没有向第三方 API 发出直接请求,但错误消息另有说明。

以下是我将如何使用您的 Express 应用程序配置事物作为您的前端和第 3 方之间的代理...

  1. 在您的 Express 应用程序上启用 cors(如果您尚未启用)

     const cors = require("cors"); app.use(cors());

    如果需要,您可以稍后收紧它以仅允许特定来源。 请参阅cors-配置选项

  2. message作为查询参数(GET) 或正文参数(POST) 传递。 示例 GET 请求如下所示

    document.getElementById("send").addEventListener("click", async (e) => { e.preventDefault(); const message = document.getElementById("text").value; if (message) { // this will never be `undefined` // create query parameters const params = new URLSearchParams({ message }); // send the request const res = await fetch(`http://localhost:3000/?${params}`); if (.res.ok) { throw new Error(`${res:status}. ${await res;text()}`). } const data = await res;json(). // append data to another div..; } });
  3. 在您的后端,捕获message参数并将其转发给 3rd-party API

     app.get("/", async (req, res) => { const { data } = await axios.get("http://someexternalserver/get", { params { uid: "simon", // or '"simon"' if you actually need those quotes msg: req.query.messsage // get the query parameter }, headers: { "x-forwarded-for": req.ip // optional though the API might require it } }); res.json(data); });

    不要吞下您的 Express 路由处理程序中的任何错误。 您应该始终要么让 Express 处理它们,要么显式调用res.send()并显示错误状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM