Nodejs如何跨域请求?带参,是用http.request(options, callback) 吗?

Nodejs如何跨域请求?带参,是用http.request(options, callback) 吗?

手头有个需求,是需要nodejs带参数发一个请求到另一台服务器上。看了本站的中文文档中,http.request(options, callback)的说明,上面说可以“/index.html?page=12” 这么传递,虽然这个可以,不过是不是太原始了?!不够模块化,有没有更好的传递参数的方法呢? 对于文档中“req.write(‘data\n’)” 这个是带参数的吗?文档中没写,自己试验没成功!

10 回复

Node.js 如何跨域请求?带参,是用 http.request(options, callback) 吗?

简介

在 Node.js 中,使用 http.request 方法进行跨域请求时,可以通过 URL 参数或请求体来传递参数。本文将展示如何使用 http.request 发送带参数的跨域请求,并提供示例代码。

使用 http.request 发送带参数的跨域请求

首先,我们来看一下如何使用 http.request 发送带有查询参数的请求:

const http = require('http');

// 定义请求选项
const options = {
    hostname: 'example.com',
    port: 80,
    path: '/api/data?page=12', // 通过 URL 的路径传递参数
    method: 'GET',
};

// 创建请求对象
const req = http.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

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

req.on('error', (error) => {
    console.error(`Problem with request: ${error.message}`);
});

// 发送请求
req.end();

在这个例子中,我们将参数 page=12 添加到 URL 的路径中,这样可以在服务器端通过查询字符串获取这些参数。

使用 querystring 模块传递查询参数

如果你更喜欢使用对象形式传递参数,可以使用 querystring 模块将其转换为查询字符串格式:

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

// 定义请求选项
const options = {
    hostname: 'example.com',
    port: 80,
    path: '/api/data?' + querystring.stringify({ page: 12 }), // 使用 querystring.stringify 将对象转换为查询字符串
    method: 'GET',
};

// 创建请求对象
const req = http.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

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

req.on('error', (error) => {
    console.error(`Problem with request: ${error.message}`);
});

// 发送请求
req.end();

总结

http.request 方法确实可以用来发送带参数的跨域请求。你可以直接将参数添加到 URL 的路径中,也可以使用 querystring 模块将对象转换为查询字符串格式。这两种方法都可以实现带参数的请求,具体选择哪种方式取决于你的需求和个人偏好。


记得上次有一帖也说这个, HTTP 请求的模块看看这个 https://github.com/visionmedia/superagent

http.request(options, callback) options是构建请求的必要参数 callback是请求成功后执行的回调函数 是没有域的限制的。

可以使用POST的方式传递数据req.write()就是向POST请求中写入传递的参数。 参见:http://nodejs.org/api/http.html#http_http_request_options_callback

在服务器端是没有跨域限制的。

看过文档渐渐明白了,req.write()的确是传递的参数,但是光写上这个是不够的,必须在options中加上 headers:{'Content-Type':'application/json','Content-Length': data.length} 如果数据是 querystring 格式则 'Content-Type':'application/x-www-form-urlencoded'

使用http.request(options, callback)方法确实可以实现跨域请求并带参数。为了更好地管理参数,我们可以利用querystring模块来构建查询字符串,这样更加模块化和易读。

以下是一个简单的示例,展示如何使用http.request方法进行跨域请求并传递参数:

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

// 请求的URL和参数
const url = 'http://example.com';
const params = {
    page: 1,
    size: 10
};

// 构建查询字符串
const queryData = querystring.stringify(params);

// 配置请求选项
const options = {
    hostname: 'example.com',
    port: 80,
    path: `/index.html?${queryData}`, // 使用拼接后的查询字符串
    method: 'GET'
};

// 发起请求
const req = http.request(options, (res) => {
    let data = '';

    res.on('data', (chunk) => {
        data += chunk;
    });

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

req.end();

解释

  1. 引入模块

    • http 模块用于发起HTTP请求。
    • querystring 模块用于处理查询字符串。
  2. 构建查询字符串

    • 使用querystring.stringify()方法将对象转换为查询字符串格式,例如 {page: 1, size: 10} 转换为 page=1&size=10
  3. 配置请求选项

    • hostnameport 是目标服务器的地址和端口。
    • path 包含URL路径以及通过querystring.stringify()生成的查询字符串。
    • method 指定请求方法,这里使用的是GET
  4. 发起请求

    • 使用http.request()方法创建请求,并提供一个回调函数处理响应。
    • 在回调函数中,监听data事件接收响应数据,并在end事件触发时打印最终结果。

这个例子展示了如何使用http.request进行跨域请求并传递参数,使代码更清晰和模块化。

回到顶部