![](/img/trans.png)
[英]Params from axios.get request are undefined on the express back end
[英]axios.get not passing params from client side to the server
作为标题, axios.get 没有将参数从客户端传递到服务器。 我的服务器当前在 localhost:3001 上,我的客户端在http://127.0.0.1:5555上。 客户端不是 React,因此它当前位于http://127.0.0.1:5555/WeatherApp/index.html上(我使用 FiveServer 在 vscode 的 chrome 上打开了 index.html 文件,即“应用程序的入口点” ,它是客户端托管的端口)
客户端代码:
export async function fetchData() {
const { data } =
await axios.get('http://localhost:3001/api', {
params: {q: 'Paris'}
})
return data
}
服务器端代码:
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)
})
服务器代码中的 console.log(req.query) 打印了一个空对象。 我也尝试了 req.params,但它也打印了一个空对象(虽然我想看到“巴黎”)。 尝试使用 console.log(req) 来查看“Paris”这个词可能嵌套在哪里,但找不到。
如果您想随请求一起发送正文,您会希望发出 POST 请求,因为您不使用它传递正文,但您可以使用 URL 中的参数以 GET 形式将信息传递给服务器要求
你可以在这里阅读更多
我正在使用这两个代码片段,它确实有效......也许你错过了一些重要的东西:
服务器.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}`)
})
客户端.js
const axios = require('axios');
axios.get('http://localhost:3000/api', {
params: {q: 'Paris'}
}).then(({data}) => console.log(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.