简体   繁体   English

axios.get 不将参数从客户端传递到服务器

[英]axios.get not passing params from client side to the server

As the title, axios.get not passing params from client side to the server.作为标题, axios.get 没有将参数从客户端传递到服务器。 My server is currently on localhost:3001, and my client side is on http://127.0.0.1:5555 .我的服务器当前在 localhost:3001 上,我的客户端在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)客户端不是 React,因此它当前位于http://127.0.0.1:5555/WeatherApp/index.html上(我使用 FiveServer 在 vscode 的 chrome 上打开了 index.html 文件,即“应用程序的入口点” ,它是客户端托管的端口)

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.服务器代码中的 console.log(req.query) 打印了一个空对象。 I also tried req.params, but it also printed an empty object (while i want to see "Paris").我也尝试了 req.params,但它也打印了一个空对象(虽然我想看到“巴黎”)。 Tried console.log(req) to see where the word "Paris" might be nested, but nowhere to be found.尝试使用 console.log(req) 来查看“Paris”这个词可能嵌套在哪里,但找不到。

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如果您想随请求一起发送正文,您会希望发出 POST 请求,因为您不使用它传递正文,但您可以使用 URL 中的参数以 GET 形式将信息传递给服务器要求

You can read more here你可以在这里阅读更多

I'm using these two code snippets and it actually works... Maybe you're missing something essential:我正在使用这两个代码片段,它确实有效......也许你错过了一些重要的东西:

server.js服务器.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客户端.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.

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