1、发送GET请求

如果你有自定义的需求,可以访问官网:

  1. let http = require('http');
  2. // 格式化返回的参数 对json格式的数据进行格式化
  3. function formatResData(data, headers) {
  4. let type = headers['content-type'];
  5. if (!type || type && type.indexOf('application/json') !== -1) {
  6. if (typeof data === 'string') {
  7. try {
  8. data = JSON.parse(data);
  9. } catch (e) { /* Ignore */ }
  10. }
  11. }
  12. return data;
  13. }
  14. // 封装get请求
  15. function get(url, headers = {}) {
  16. return new Promise((resolve, reject) => {
  17. const options = {
  18. headers: headers
  19. };
  20. const req = http.get(url, options, res => {
  21. let had = false;
  22. res.setEncoding('utf8');
  23. // 监听返回的数据
  24. res.on('data', (chunk) => {
  25. had = true;
  26. // 数据格式化
  27. res.data = formatResData(chunk, res.headers);
  28. resolve(res);
  29. });
  30. // 监听接口请求完成, 除非error,最终都会执行end;
  31. res.on('end', () => {
  32. if (had) return;
  33. resolve(res);
  34. });
  35. });
  36. req.on('error', e => {
  37. reject(e);
  38. });
  39. }).catch(e => {
  40. console.error('Request error: ' + url + ', Method:' + 'GET' + ',Error message:', e);
  41. throw new Error(e ? e : 'Request error');
  42. })
  43. }

从服务器取出资源(一项或多项)
GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连
如果要在query部分带参数 (包括PUT POST DELETE)
如:

  1. http://www.helloworld.com/messages/topic3?/messages/topic3?cmd=event&uid=A15C2DB&img=1

均需要使用qs模块进行处理:

  1. // 调用示例
  2. let headers = {
  3. Cookie: 'xxxxxx'
  4. };
  5. get('http:xxxxxx', headers).then(res => {
  6. // res.statusCode为接口返回的状态码, res.data为接口返回的数据
  7. console.log(res.statusCode, res.data);
  8. });

2、发送POST请求

  1. let http = require('http');
  2. // 封装POST请求
  3. function post(url, data, headers = {}) {
  4. return new Promise(resolve => {
  5. const options = {
  6. method: 'POST',
  7. headers: headers
  8. };
  9. const req = http.request(url, options, res => {
  10. let had = false;
  11. res.setEncoding('utf8');
  12. res.on('data', (chunk) => {
  13. had = true;
  14. // 当接口返回的是json格式数据时可以使用JSON.parse
  15. res.data = formatResData(chunk, res.headers);
  16. resolve(res);
  17. });
  18. // 监听接口请求完成, 除非error,最终都会执行end;
  19. res.on('end', () => {
  20. if (had) return;
  21. resolve(res);
  22. });
  23. });
  24. req.on('error', e => {
  25. reject(e);
  26. });
  27. // 写入请求的数据
  28. data && req.write(data);
  29. req.end();
  30. }).catch(e => {
  31. console.error('Request error: ' + url + ', Method:' + 'GET' + ',Error message:', e);
  32. throw new Error(e ? e : 'Request error');
  33. })
  34. }
  1. // 调用示例
  2. let data = {
  3. name: 'xxx'
  4. }
  5. // 发送form表单格式数据
  6. data = qs.stringify(data);
  7. // 设置请求头(Content-Type)为form表单格式
  8. let headers = {
  9. 'Content-Type': 'application/x-www-form-urlencoded',
  10. 'Cookie': 'xxxxx'
  11. };
  12. post('http:xxx', data, headers).then(res => {
  13. // res.statusCode为接口返回的状态码, res.data为接口返回的数据
  14. console.log(res.statusCode, res.data);
  15. })

3、发送PUT请求

在服务器更新资源(客户端提供改变后的完整资源)

  1. var request = require("request");
  2. var options = {
  3. url: 'http://xxxxxxxx.s3.us-east-1.amazonaws.com' +s3_path,// ,
  4. headers: {
  5. host: 'jwlipirtest.s3.amazonaws.com',
  6. 'x-amz-content-sha256':'UNSIGNED-PAYLOAD',
  7. 'x-amz-date':date,
  8. Authorization: result
  9. },
  10. body:bitmap
  11. };
  12. request.put(options, function(error, response, body) {
  13. console.info('response:' + JSON.stringify(response));
  14. console.info("statusCode:" + response.statusCode)
  15. console.info('body: ' + body );
  16. });

4、发送Delete请求

从服务器删除资源。

  1. var request = require("request");
  2. var options = {
  3. url:'http://172.28.28.4:3017/files/testhttp',
  4. headers:{
  5. uid:"xxxxxxxx"
  6. },
  7. form:{
  8. target:"/user/one"
  9. }//req.body
  10. };
  11. request.del(options, function(err, response, body){
  12. console.info(response.body);
  13. });

5、node开启的服务支持跨域

  1. 如果你需要在请求头接受cookieToken进行权限验证,'Access-Control-Allow-Headers'里面需要添加Set-Cookie和接受的请求头名称,例如下面的例子中Authorization为接受的请求头名称。
  1. var app = express();
  2. // 允许跨域
  3. app.use((req, res, next) => {
  4. res.set({
  5. 'Access-Control-Allow-Credentials': true, //允许后端发送cookie
  6. 'Access-Control-Allow-Origin': req.headers.origin || '*', //任意域名都可以访问,或者基于我请求头里面的域
  7. 'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type,Set-Cookie,Authorization', //设置请求头格式和类型
  8. 'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
  9. 'Content-Type': 'application/json; charset=utf-8'//默认与允许的文本格式json和编码格式
  10. })
  11. req.method === 'OPTIONS' ? res.status(200).end() : next()
  12. })