Cross domains – JSONP, WebPack, koA2-CORS address cross domains
The book follows on from the previous chapter: Cross domains — understanding its nature step by step through code. In the last chapter, we simply set up the front and back end separation project locally, and understood the cross-domain from the code level. This chapter is our practice, the complete code is on my Git, read readme to get the correct posture. This chapter is as follows:
- Jsonp principle analysis
- Koa projects introduce KOA-CORS to solve cross-domain problems
- Solve problems during webpack project development
jsonp
The main purpose of JSONP is to allow web pages to retrieve data from other domain names, that is, cross-domain resource retrieval. Script is not applicable to the same origin policy, through SRC can request data from other domain names.
Code implementation
Client code
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial scale=1.0"> <title>Document</title> </head> <body> <script type="text/javascript"> function callback(result) { The console. The log (result)} < / script > < script type = "text/javascript" SRC = "http://127.0.0.1:3000/jsonp? callback=callback"> </script> </body> </html>Copy the code
Server code
router.get('/jsonp', Async (CTX) = > {/ / get the callback function name let callbackName = CTX. Query. The callback | | 'callback' / / return data definition let returnData = {success: true, data: { text: 'this is a jsonp api', time: New Date().getTime(),}} // return js code (i.e. : Let jsonpStr = '${callbackName}(${json.stringify (returnData)})' // Set content-type ctx. Type = 'text/javascript' ctx.body = jsonpStr })Copy the code
The principle of analysis
- The first script on the client side defines the callback function
- The second script sends the request with the name of the callback function
- The server assembles the JS code that performs the callback
- The client gets the BACKGROUND JS code and executes it
- Get the data
Ps: JSONp is only used with GET requests
koa-cors
Typically cross-domain is handled by the back end. Each language needs a corresponding third-party package for processing. For KOA2 projects, the introduction of KOA2-CORS solves the problem
// Resolve cross-domain issues
app.use(cors({
exposeHeaders: ['WWW-Authenticate'.'Server-Authorization'].maxAge: 5.// Allow cookies to be received
credentials: true.allowMethods: ['GET'.'POST'.'DELETE'.'PUT'].allowHeaders: ['Content-Type'.'Authorization'.'Accept'],}))Copy the code
Webpack-dev proxy configuration addresses cross-domain
This mode only uses the development mode and is configured in webpack.config.js or vue-config.js as follows
DevServer: {// Enable hot update hot: true, port: 3000, contentBase: path.resolve(__dirname, '.. /dist'), compress: true, proxy: {'/ API ': {target: 'http://10.10.0.135:8899', changeOrigin: True, // domain name secure: false, // Whether HTTPS pathRewrite: {'^/ API ': "} // rewrite url},}}Copy the code
Note how to understand pathRewrite
-
Take the appeal code. Under no path to rewrite: / API/xx agency for http://127.0.0.1:3000/api/xx
-
In the case of path overrides :/ API /xx proxy is http://127.0.0.1:3000/xx