简体   繁体   English

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

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

I have a frontend (html) and Node.js backend (express).我有一个前端 (html) 和 Node.js 后端 (express)。 I want to make a request to a 3rd party api but having cors issues.我想向第三方 api 提出请求,但有 cors 问题。

Now I want to be able to grab the value of an input and append it to my backend url upon request on frontend (eg localbackend:3000/${input_value} ), then use the passed parameter ( input_value ) in my backend to form the api url that I need to make a call to the external api.现在我希望能够根据前端的请求(例如localbackend:3000/${input_value} )将输入的值和 append 抓取到我的后端 url ,然后在我的后端使用传递的参数( input_value )来形成api url 我需要拨打外部api。

A bit of code:一些代码:

index.html index.html

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

index.js索引.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... 

server.js服务器.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);
    });
});

Manually I am able to successfully test the external api but I want this done dynamically.手动我能够成功测试外部 api 但我希望动态完成。

Feel free to share a better solution or simply how to get this working.随意分享更好的解决方案或简单地分享如何让它工作。 No FE frameworks please.请不要使用 FE 框架。

I tried:我试过了:

Rob's cors-anywhere ( https://cors-anywhere.herokuapp.com/ ) proxy which the api has restricted. Rob 的 cors-anywhere ( https://cors-anywhere.herokuapp.com/ ) 代理已被 api 限制。

Something seems wrong.似乎有些不对劲。 Your frontend app doesn't appear to be making a direct request to the 3rd-party API but the error message says otherwise.您的前端应用程序似乎没有向第三方 API 发出直接请求,但错误消息另有说明。

Here's how I would configure things with your Express app acting as a proxy between your frontend and the 3rd-party...以下是我将如何使用您的 Express 应用程序配置事物作为您的前端和第 3 方之间的代理...

  1. Enable cors on your Express app if you haven't already在您的 Express 应用程序上启用 cors(如果您尚未启用)

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

    You can tighten this up later to only allow specific origins if you want.如果需要,您可以稍后收紧它以仅允许特定来源。 See cors - configuration options .请参阅cors-配置选项

  2. Pass the message as a query parameter (GET) or body parameter (POST).message作为查询参数(GET) 或正文参数(POST) 传递。 An example GET request would look like this示例 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. In your backend, capture the message parameter and forward it to the 3rd-party API在您的后端,捕获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); });

    Don't swallow up any errors in your Express route handlers.不要吞下您的 Express 路由处理程序中的任何错误。 You should always either let Express handle them or explicitly call res.send() with an error status.您应该始终要么让 Express 处理它们,要么显式调用res.send()并显示错误状态。

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

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