Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  158] [ 5]  / answers: 1 / hits: 7064  / 3 Years ago, tue, september 14, 2021, 12:00:00

So i'm making a fetch request from react to express and the api url requires params but I want the last bit of the url to be dynamic. How would I send a param from react to the api url in express? Heres the code


react


const [dynamic, setDynamic] = useState("somevalue")

useEffect(() => {
async function fetchData() {
const response = await fetch("/web")
const data = await response.json()
console.log(data)
}
fetchData()
}, [dynamic])

express.js


app.get("/web", async (req, res) => {
const response = await fetch("https://alexa.com/api?Action=urlInfo&Url=")
const data = await response.json()
res.json(data)
})

Basically, I would like the dynamic state value to be injected into the end of the URL in express.


Something like


react


const [dynamic, setDynamic] = useState("somevalue")

async function fetchData() {
const response = await fetch("/web" + dynamic)
const data = await response.json()
console.log(data)
}

Then in express when the API is called the URL changes to


const response = await fetch("https://alexa.com/api?Action=urlInfo&Url=somevalue")

How can I go about achieving this?


More From » reactjs

 Answers
8

You define the parameter on the route handler side, setting up a route that matches the desired pattern. For example:


app.get("/foo/bar/:myparam", async (req, res) => {
//... here's your handler code
})

Will match /foo/bar/baz, and req.params.myparam === "baz" inside the handler.


http://expressjs.com/en/guide/routing.html#route-parameters


Using query params is similar, but you want to check the values of the req.query object instead, like:


// client side (React code)
await fetch("/foo/bar?myparam=baz")
...
// In your express handler:
req.query.myparam === "baz"

[#873] Wednesday, September 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyonnaelled

Total Points: 35
Total Questions: 113
Total Answers: 99

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
keyonnaelled questions
Wed, Oct 14, 20, 00:00, 4 Years ago
Tue, Sep 8, 20, 00:00, 4 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
;