Cross-domain solutions

Protocol, domain name, port number, as long as there is a different is a cross-domain requestCopy the code
1. Reasons for cross-domain existence
+ Servers deployed separately: WEB server, data server, image server... (Separate deployment helps rational utilization of server resources.) + Local development: Local preview project retrives data from the test server + retrives third-party platform API interfaceCopy the code
2. Main cross-domain solutions
Only three kinds of + JSONP + CORS + ProxyCopy the code
(1) the json
JSONP: Cross-domain requests using SCRIPT tags that do not have domains (A) Callback must be A function in the global context. (B) Callback must be A function in the global context. (C) Callback must be A function in the global context.Copy the code
Function request(url = "", callback) {let script; Let name = 'jsonp${new Date().getTime()}' window[name] = (data) => {// data gets the result from the server document.body.removeChild(script); delete window[name]; callback && callback(data); } URL += '${url.includes('? ')? '&' : '? '}callback=${name} '// send request script = document.createElement('script') script.src = url document.body.appendChild(script); } the request (' http://127.0.0.1:8099/list ', the result = > {the console. The log (result); }); // server code let HTTP = require(' HTTP ') let fs = require('fs') let url = require('url' http.createServer((req, res)=>{ let { pathname, Query} = url.parse(req.url) let callback = query.split('=')[1] // request if(pathName == '/list'){  code: 0, data: [10, 20] }; let str = `${callback}(${JSON.stringify(result)})`; res.end(str); }}) server. Listen (8099, () = > {the console. The log (' 8099 interface request success ')})Copy the code
(2) the CORS
'access-Control-allow-origin ': (1) * : allows all sources to be insecure; Cannot carry resource credentials; (2) set single source security; Can carry resource credentials (only a single source); Allow-origin = allow-origin = allow-Origin = allow-Origin = allow-Origin = allow-OriginCopy the code
/ / front end get onclick = function () {the fetch (' http://127.0.0.1:8099/list '{credentials: 'include', }).then(res => res.text()).then(data => {console.log(data)})} // whitelist let allowOrigin = ['http://127.0.0.1:8099', 'http://127.0.0.1:5500', 'http://127.0.0.1:5502'] let server = http.createserver ((req, res) => {// Set the allowed source // * : Allow all sources (insecure/cannot carry resource credentials) // Set a single source (secure/can also carry resource credentials/can only be a single source) // Can dynamically set multiple sources: Every request goes through this middleware. We first set up a whitelist. If the source of the current client request is in the whitelist, If (alloworigin.includes (req.headers. Origin)) {if (alloworigin.includes (req.headers. Origin)) { res.setHeader('Access-Control-Allow-Origin', req.headers.origin) res.setHeader('access-control-allow-credentials', Setcookie res.setHeader(' set-cookie ', ['a=123; SameSite=Secure']) let {pathname} = url.parse(req.url) Method === 'OPTIONS' in CORS cross-domain requests, the browser sends a trial request to verify that it can communicate with the server. The server returns 200, and the browser continues to send the real request. res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS! ') : next(); If (pathName == '/list') {let result = {code: 0, data: [10, 20]}; res.end(JSON.stringify(result)); }}) server.listen(8099, () => {console.log('8099 interface request succeeded ')})Copy the code
(3) the Proxy
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'production',
    entry: './src/main.js',
    output: {
        filename: 'main.[hash].min.js',
        path: path.resolve(__dirname, 'build')
    },
    devServer: {
        port: '3000',
        compress: true,
        open: true,
        hot: true,
        proxy: {
            '/': {
                target: 'http://127.0.0.1:3001',
                changeOrigin: true
            }
        }
    },
    // 配置WEBPACK的插件
    plugins: [
        new HtmlWebpackPlugin({
            template: `./public/index.html`,
            filename: `index.html`
        })
    ]
}
Copy the code