乐闻世界logo
搜索文章和话题

How can I send cookie using NodeJs request GET module?

1个答案

1

In Node.js, sending HTTP GET requests with cookies can typically be achieved using popular libraries such as axios or request (which is deprecated but still has extensive examples and documentation). Below, I will use axios as an example to demonstrate how to send a GET request with cookies. First, ensure that axios is installed. If not, install it using npm: bash npm install axios Next, we can write a simple function to send a GET request with cookies. Here is an example code snippet: ```javascript const axios = require('axios');

async function sendGetRequestWithCookie(url, cookie) { try { const response = await axios.get(url, { headers: { 'Cookie': cookie } }); console.log('Status Code:', response.status); console.log('Body:', response.data); } catch (error) { console.error('Error during the HTTP request:', error.message); } }

// Usage example const url = 'http://example.com/data'; const cookie = 'sessionid=123456789; username=johndoe'; sendGetRequestWithCookie(url, cookie); ``` In the above code, the second parameter of the axios.get method is a configuration object that includes the headers property. We set the Cookie header through this property, with the value being the cookie string we intend to send. This approach is suitable for scenarios where authentication information or session information needs to be included with the request, such as accessing a page that requires login. This example demonstrates how to use the axios library in Node.js to send an HTTP GET request with cookies. By adjusting the headers object, we can also send other types of HTTP header information.

2024年8月12日 14:25 回复

你的答案