As the title, axios.get not passing params from client side to the server. My server is currently on localhost:3001, and my client side is on http://127.0.0.1:5555. Client side is not React, so it's currently on http://127.0.0.1:5555/WeatherApp/index.html (I opened the index.html file, the "entry point of the app," on chrome from vscode by using FiveServer, and it is the port the client is being hosted)
Client side code:
export async function fetchData() {
const { data } =
await axios.get('http://localhost:3001/api', {
params: {q: 'Paris'}
})
return data
}
Server side code:
app.get("/api", async (req, res) => {
console.log(req.query)
const response = await axios.get('http://api.weatherapi.com/v1/current.json', {
params: {
key: process.env.KEY,
q: 'Paris'
}
})
const { data } = response
res.send(data)
})
The console.log(req.query) in server code printed an empty object. I also tried req.params, but it also printed an empty object (while i want to see "Paris"). Tried console.log(req) to see where the word "Paris" might be nested, but nowhere to be found.
CodePudding user response:
If you want to send a body with your request, you'd be looking to make a POST request, as GET as you dont pass a body with it, but you can use parameters in your URL to pass information to the sever in a GET request
You can read more here
CodePudding user response:
I'm using these two code snippets and it actually works... Maybe you're missing something essential:
server.js
const express = require('express')
const app = express()
const port = 3000
app.get('/api', (req, res) => {
console.log(req.query)
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
client.js
const axios = require('axios');
axios.get('http://localhost:3000/api', {
params: {q: 'Paris'}
}).then(({data}) => console.log(data));