简体   繁体   English

从 HTTP GET 请求中获取数据

[英]Get data from HTTP GET request

I'm sending an HTTP GET request from the client to my server.我正在从客户端向我的服务器发送 HTTP GET 请求。 On the server, I can't access the data that is passed with the GET request.在服务器上,我无法访问通过 GET 请求传递的数据。 It works for POST requests but the value is not received in the get request.它适用于 POST 请求,但在 get 请求中未收到该值。

The client is Vue.js, and the Server is Express.js in Node.js. Client是Vue.js,Server是Node.js中的Express.js。 The code looks like this.代码看起来像这样。

Client:客户:

var response = await axios.get('/endpoint',{ key: 'value' });

Server:服务器:

router.get('/endpoint', async (req,res) => {
    console.log(req.body); // empty
    console.log(req.query);  // empty
    console.log(req.params); // empty
});

I've set up my body-parser above.我已经在上面设置了我的body-parser It looks like below它看起来像下面

const bodyparser = require('body-parser');
app.use( bodyparser.json() );

How do I access the {key: 'value'} object that is sent from the client in my server.如何访问从我的服务器中的客户端发送的 {key: 'value'} object。

GET requests do not have bodies GET 请求没有正文

I believe the problem is that you want to access body by我相信问题是你想通过

console.log('req.body');

instead of代替

console.log(req.body);

Also, as pointed above, GET doesn't have body.此外,如上所述,GET 没有正文。

With Axios you can path query params to GET call in 2 different ways:使用 Axios,您可以通过 2 种不同的方式将查询参数路由到 GET 调用:

  1. By putting them into the endpoint path通过将它们放入端点路径

await axios.get('/endpoint?key=value&key2=value2');

  1. Add them to the config argument in params property object as key-value将它们作为键值添加到params属性 object 中的配置参数中

await axios.get('/endpoint', { params: {key: 'value', key2: 'value2' }});

Your confusion absolutely makes sense, you try to use same way to pass param for get and post methods, but in Axios these methods have different number of arguments: post(url, data, config), get(url, config)您的困惑绝对是有道理的,您尝试使用相同的方式为 get 和 post 方法传递参数,但是在 Axios 中,这些方法具有不同数量的 arguments:post(url, data, config), get(url, config)

Let's return to your example: var response = await axios.get('/endpoint',{ key: 'value' });让我们回到您的示例: var response = await axios.get('/endpoint',{ key: 'value' });

So now you can see that { key: 'value' } object that you pass as a second argument is request config and isn't a data.所以现在您可以看到作为第二个参数传递{ key: 'value' } object 是请求配置,而不是数据。

You can learn more about request config params here - https://github.com/axios/axios#request-config您可以在此处了解有关请求配置参数的更多信息 - https://github.com/axios/axios#request-config

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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