nodejs sends http request parameters

王林
Release: 2023-05-28 09:26:37
Original
981 people have browsed it

It is more common to send HTTP requests in Node.js by using the http and https modules. These modules provide powerful and flexible methods to send HTTP requests. In this article, we will discuss how to send HTTP requests in Node.js and include parameters in the request.

http module sends HTTP requests

In Node.js, we can use the http module to send HTTP requests. Let's look at a simple example:

const http = require('http');

const options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/submit',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  }
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);
  
  res.on('data', (data) => {
    console.log(data.toString());
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(JSON.stringify({ key: 'value' }));
req.end();
Copy after login

In the above example, we use the http.request() method to create an HTTP request and pass options The object specifies the requested URL, port, path, and method. We also set the request header to specify that the request body is formatted as JSON.

Then, we call the req.write() method to serialize the parameters to be sent into a JSON string, and call the req.end() method to Complete the HTTP request.

Finally, we define the req object's on('error') and res.on('data') events to handle Exceptions and response data during request and response processes.

Send GET request

When sending a GET request, we can pass parameters by adding query parameters in the URL. For example:

const http = require('http');

const query = 'q=nodejs';
const options = {
  hostname: 'www.example.com',
  port: 80,
  path: `/search?${query}`,
  method: 'GET'
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (data) => {
    console.log(data.toString());
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.end();
Copy after login

In the above example, we use the query parameter q=nodejs in the URL to search for the target resource, and add the query parameter to the path attribute middle.

Send POST request

When sending a POST request, we usually need to send some data to the server. This data can be form data or JSON data, etc. We need to encode the data in a specified format and send it to the server.

Sending form data

Let's look at an example of sending form data to the server. We need to use the querystring module to encode the form data into a URL query string.

const http = require('http');
const querystring = require('querystring');

const formData = {
  name: 'John Doe',
  email: 'johndoe@example.com',
  message: 'Hello, world!'
};

const postData = querystring.stringify(formData);

const options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/contact',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (data) => {
    console.log(data.toString());
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(postData);
req.end();
Copy after login

In the above example, we defined an object named formData which contains the form data to be sent. We encode this into a URL query string using the querystring.stringify() method and set it as the request body of the POST request. We also define the request header to specify the format of the request body as application/x-www-form-urlencoded.

Send JSON data

In addition to sending form data, we can also send JSON data. We need to serialize JSON data using the JSON.stringify() method.

const http = require('http');

const jsonData = { 
  name: 'John Doe',
  email: 'johndoe@example.com',
  message: 'Hello, world!'
};

const postData = JSON.stringify(jsonData);

const options = {
  hostname: 'www.example.com',
  port: 80,
  path: '/api',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': postData.length
  }
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (data) => {
    console.log(data.toString());
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(postData);
req.end();
Copy after login

In the above example, we define a JSON object named jsonData and use the JSON.stringify() method to encode it into JSON characters string. We also define the request header to specify the format of the request body as application/json.

Summary

This article describes how to send HTTP requests containing parameters in Node.js. We used the http module, for more detailed documentation on the http module, see the Node.js documentation.

The above is the detailed content of nodejs sends http request parameters. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template