I have a frontend (html) and Node.js backend (express). I want to make a request to a 3rd party api but having cors issues.
Now I want to be able to grab the value of an input and append it to my backend url upon request on frontend (e.g 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.
A bit of code:
index.html
<input type="text" id="text">
index.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
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.
Feel free to share a better solution or simply how to get this working. No FE frameworks please.
I tried:
Rob's cors-anywhere (https://cors-anywhere.herokuapp.com/) proxy which the api has restricted.
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.
Here's how I would configure things with your Express app acting as a proxy between your frontend and the 3rd-party...
Enable cors on your Express app if you haven't already
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.
Pass the message as a query parameter (GET) or body parameter (POST). An example GET request would look like this
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...
}
});
In your backend, capture the message parameter and forward it to the 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. You should always either let Express handle them or explicitly call res.send() with an error status.