Home  >  Article  >  Web Front-end  >  nodejs set service proxy cross domain

nodejs set service proxy cross domain

WBOY
WBOYOriginal
2023-05-25 12:19:38973browse

With the rapid development of Internet technology, the ways of transmitting data are becoming more and more diverse. However, transferring data across domains is a problem due to various security restrictions. This article will introduce how to use Node.js to set up a service proxy across domains.

1. What is cross-domain

Cross-domain means that when the client requests resources under another domain name through Ajax, the browser will comply with the same-origin policy and find that the request is cross-domain Requests from non-original sources will be blocked. Therefore, cross-domain requests often fail due to security policies.

2. Why cross-domain requests are needed

The emergence of cross-domain requests is mainly to facilitate data interaction between various sites. For example, when we access a web application, we may need to obtain data from different sites. In this case, cross-domain requests are necessary.

3. Cross-domain solution

  1. JSONP (JSON with Padding) realizes cross-domain

JSONP is a standard cross-domain solution , which dynamically creates script tags, wraps data in callback functions and returns them together.

  1. CORS (Cross-Origin Resource Sharing) realizes cross-domain

The CORS specification is a cross-domain resource sharing standard developed by W3C. By setting Access on the server -Control-Allow-Origin response header to solve cross-domain issues. However, CORS is only supported in advanced browsers, and is not supported by lower version browsers.

4. Use Node.js to implement cross-domain service proxy

Cross-domain service proxy refers to sending a request to the server of the same source, and then the server proxy requests data from the target server , thereby implementing cross-domain requests. The following is sample code for using Node.js to implement service proxy cross-domain.

//导入所需的模块
const http = require('http');
const https = require('https');
const url = require('url');
const querystring = require('querystring');

//创建HTTP服务器
http.createServer(function(req,res) {
  //获取请求URL
  let aimUrl = req.url;

  //解析请求地址
  let urlObj = url.parse(aimUrl,true);

  //获取目标地址
  let targetUrl = urlObj.query.url;

  //解析参数
  let paramsObj = urlObj.query;

  //删除URL中的url参数
  delete paramsObj.url;

  //将JSON格式的querystring参数转化为querystring
  let params = querystring.stringify(paramsObj);

  //设置目标URL
  let options = {
    protocol: url.parse(targetUrl).protocol,
    hostname: url.parse(targetUrl).hostname,
    port: url.parse(targetUrl).port,
    path: url.parse(targetUrl).pathname + '?' + params,
    method: 'GET',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  };

  //发起请求
  let request = https.request(options, function(response) {
    //设置响应数据类型
    res.writeHead(response.statusCode, {'Content-Type': 'application/json'});

    //监听data事件
    response.on('data', function(chunk) {
      res.write(chunk);
    });

    //监听end事件
    response.on('end', function() {
      res.end();
    });
  });

  //设置请求超时时间
  request.setTimeout(3000, function() {
    res.writeHead(500, {'Content-Type': 'application/json'});
    res.write(JSON.stringify({error: 'timeout'}));
    res.end()
  });

  //监听错误事件
  request.on('error', function(error) {
    res.writeHead(500, {'Content-Type': 'application/json'});
    res.write(JSON.stringify({error: error}));
    res.end();
  });

  //设置请求方式
  request.method = req.method;

  //发起请求
  if (req.method == 'POST' || req.method == 'PUT') {
    req.on('data', (data) => {
      request.write(data);
    });
    req.on('end', () => {
      request.end();
    });
  } else {
    request.end();
  }
}).listen(8080, 'localhost');

5. Summary

This article introduces the principle of cross-domain requests and two common cross-domain solutions (JSONP and CORS), and also uses Node.js to implement service proxy cross-domain This method solves the problem of cross-domain requests by making data requests on the server side. Server-side cross-request is a safe and stable method, which can make cross-domain requests more secure and suitable for various complex scenarios.

The above is the detailed content of nodejs set service proxy cross domain. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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