nodejs solves front-end cross-domain back-end access to third-party interfaces

Due to the browser's same-origin policy, using ajax to access a third-party interface will report a cross-domain error.

The solution, 1, use nginx to set up the front-end website, and configure the proxy in nginx.

                   2. Write the back-end code yourself, access the third-party interface through the back-end, and send the data returned by the third-party interface to the front-end.

Let's talk about the second method first: back-end code

const http=require('http');
const querystring=require('querystring');
const superAgent=require('superagent');
const url=require('url');
const db=require('./db');

http.createServer(function(req,res){
  var postData='';

    var params=url.parse(req.url,true).query;
    var proxy_url=params.url.replace(/\$/g,'&')
    console.log('proxy:',proxy_url)
    res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
    var sreq=superAgent.get(proxy_url)
    sreq.pipe(res);
    sreq.on('end',()=>{
        console.log('done')
    })
    
}).listen(3000);
console.log( "Service started...")

The superagent module is used here. Since I separate the front and back ends, I have configured the domain names that allow cross-domain access:

http://127.0.0.1:5500 This is the domain name + port number of my front-end service. 

Front-end code:
 let url=this.tokenUrl+'userid='+this.userid+'&password='+this.password+'&resource='+this.resource
 url=url.replace(/&/g,'$')
axios.get('http://localhost:3000?url='+url,{
            //responseType: 'document'
        }).then((res)=>{
            console.log(res.data)
        })

The front-end code is mainly to access the back-end service just started, and I use the get request of axios. The parameter url is the third-party interface address that the backend needs to help access.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324597242&siteId=291194637