Cross domain
Definition:
- If the protocol, domain name, or port is different, the data requests are called cross-domain requests
The same-origin restrictions
- Unable to make Ajax request cannot share cookie
The option to request:
-
The browser initiates a precheck request to the target server for cross-domain requests that are not simple requests
-
The purpose is to determine whether the actual request being sent is secure.
-
What is a simple request
- When it’s not get or POST it’s basically a complex request
- Get or POST requests can also become complex requests with custom headers, causing the browser to trigger precheck
Node implements CORS:
Initialize the
- npm init -y
- Live -server: vscode plug-in installed, always start a different port server for cross-domain request preparation
html
- Btn. addEventListener listens for the click event
- XHR = new XMLHttpRequest() in click event
- xhr.open(“POST”, “http://localhost:3000/login”, true); Implement dynamic file requests
- Static files: the browser makes simple requests to the server that do not change (HTML, js, img..). ,;
- Dynamic file: when a browser accesses this resource, the source code of the resource may send changes
- Turn a POST request into a complex request with setRequestHeader
SetRequestHeader specifies the type of data that the client passes to the server. The latter specifies the type of data that the client asks the server to return
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, </title> Document</title> </head> <body> <button id=" BTN "> click </button> <script> btn.addEventListener("click", () => { const xhr = new XMLHttpRequest(); The default server port / / I am here is 3000 XHR. Open (" POST ", "http://localhost:3000/login", true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.responseType = "json"; Xhr.onload = function () {// The browser will parse console.log(xhr.response) based on the type returned; }; Xhr. send('{"name":"ZOE"}'); }) </script> </body> </html>Copy the code
js
-
Create a service and listen on port 3000
-
Check whether there is a cross-domain request header. The browser has its own Origin header.
-
Access-control-allow-origin Whitelist configuration
-
Access-control-allow-headers Allows custom request Headers
-
Access-control-max-age Allows cross-domain requests within a fixed period of time without the need to repeatedly initiate option requests.
-
The handling of null returns when option requests
No:
- Obtain the request path to determine whether it is a file or a file directory
- None of them return 404
- If the directory is a file directory, find the corresponding directory in index.html &fs.access to check whether it is accessible.
Do not visit
Ask also returns 404;Can be accessed
Use readable stream (Fs.createreadStream) + pipe to read the file content, use MIME to obtain the file content format, and set the encoding specification to UTF-8 - If the file is directly read with readable stream (fs.createreadStream) + pipe (pipe) file content read default text/ HTML format + UTF-8 encoding
Do common request processing
-
const http = require("http"); const url = require("url"); const fs = require("fs"); const path = require("path"); const mime = require("mime"); const server = http.createServer((req, res) => { let { pathname, query } = url.parse(req.url, true); If (req.headers. Origin) {if (req.headers. Origin) {if (req.headers. Origin) { Res.setheader (" access-Control-allow-origin ", req.headers. Origin); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.setHeader("Access-Control-Max-Age", "10"); res.setHeader("Access-Control-Allow-Credentials", true); if (req.method === "OPTIONS") { return res.end(); If (pathName === "/login" &&req.method === "POST") {// File read req.on("data", (chunk) => { buffer.push(chunk); }); Req.on ("end", () => {let buf = buffer.concat (Buffer); If (req.headers["content-type"] === "application/json") {let obj = json.parse (buf.tostring ()); // The string res.setheader (" content-type ", "application/ Json ") is displayed. // Write the response to the browser's data res.end(json.stringify (obj)); } else if (req.headers["content-type"] === "text/plain") { res.setHeader("Content-Type", "text/plain"); // Write the response to the browser's data res.end(buf.tostring ()); } else {// Res.end ("ok") is not supported for content-type; }}); }else {// Static file request logic code let filePath = path.join(__dirname, pathname); Fs. stat(filePath, function (err, StatObj) {return 404 if (err) {res.statusCode = 404; res.end("NOT FOUND"); } else {// If it is a file, use mime to read the file. If (statobj.isfile ()) {res.setheader (" content-type ", mime.getType(filePath) + "; charset=utf-8" ); fs.createReadStream(filePath).pipe(res); } else {// Let htmlPath = path.join(filePath, "index.html");} else {// Let htmlPath = path.join(filePath, "index.html"); Fs. access(htmlPath, function (err) {if (err) {404 res.statusCode = 404; res.end("NOT FOUND"); Res.setheader (" content-type ", "text/ HTML; charset=utf-8"); fs.createReadStream(htmlPath).pipe(res); }}); }}}); } }) server.listen(3000, () => { console.log("server start 3000"); });Copy the code
The test results
- The cross-domain request was successfully implemented
- The option request is not repeated within 10 seconds
- Disable cache cannot be checked to allow local caching
summary
There are many kinds of cross-domain solutions, such as jSONP, IFrame, Nginx direction proxy, WebSocket; However, CORS should be a cross-domain solution with relatively more applications, so there is today’s practice + summary
Finally, if you find this article helpful, please remember to like three times oh, thank you very much