Front knowledge
When the CORS word is found in the Network and the request fails, it is cross-domain
Why cross domains
When your request is different from your current url, including domain name, protocol, or port, the browser will block the request
Cross-domain is a browser problem, because browsers have the same origin policy and the request is not going to be sent
Handling cross-domain methods
JSONP
The browser’s same origin policy values are Ajax-specific and can be used to request resources from different sources via the SRC script tag, but it can only support GET requests, so to support all HTTP requests, you must use CORS or some other proxy method
CORS
The work of the browser is automatically completed. Developers are more like other Ajax requests. The browser finds that cross-domain Ajax requests will automatically add some header information, but the user does not perceive it
There are two ways to request CORS
A simple request
A request that meets the following two conditions is a simple request
1) The request method is one of the following: HEAD GET POST 2) The HTTP header does not exceed the following fields: Accept accept-language content-language last-event-id Content-type: Application/X-www-form-urlencoded, multipart/form-data, text/plain are limited to three valuesCopy the code
This is compatible with forms, so forms can send cross-domain requests, and ajax can send requests that forms can send
If it is a simple request, the browser will add the origin field in the header to indicate the source of the request. If the source is not in the licensed range, the browser will report an error. If it is in the licensed range, the browser will add this field in the server response header
Access-Control-Allow-Origin: http://xxx.com
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: FooBar
Content-Type: text/html; charset=utf-8
Copy the code
Access-control-allow-origin Specifies the mandatory domain name that can be accessed. * indicates that all domain names are allowed
Access-control-allow-credentials Optional field, indicating whether cookies are allowed to be sent. By default, cookies are not included in CORS requests. Setting it to true allows cookies to be sent along with the request. If not, delete this field.
The browser sends cookies to the server. In addition to allowing the server to configure the above fields, the front end also needs to enable the withCredentials attribute in the Ajax request. The browser will also send cookies if omitted, and can display them off if not needed
let xhr = new XMLHttpRequest();
xhr.withCredentials = true;
Copy the code
Note: If cookies are to be sent, access-Control-allow-origin cannot be set to * and must be explicitly specified and requested
Access-control-expose-headers Optional. The getResponseHeader() method of the XMLHttpRequest object only gets six basic fields when CORS requests it
Non-simple request
For example, the request is put, or the Content-Type field is Application/JSON
Non-simple requests are prechecked with the first HTTP request, in which the browser asks if the current domain name is on the server’s approved list, along with the header, and can only be sent if a positive response is reached.
Here is the HTTP header for the precheck request
OPTIONS /cors HTTP/1.1
Origin: http://xxx.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
Copy the code
The precheck request method is OPTINS, which is used to ask,
Access-control-request-method Specifies the HTTP methods that the Request will reach
The configuration process
- Download Express and HTTP-proxy-Middleware
yarn add express http-proxy-middleware
Copy the code
- Create server.js in the root directory
//server.js const express = require('express') const next = require('next') const { createProxyMiddleware } = Require ('http-proxy-middleware') const devProxy = require('./proxy') const port = parseInt(process.env.port, 10) || 3000 const dev = process.env.NODE_ENV ! == 'production' const app = next({ dev }) const handle = app.getRequestHandler() app .prepare() .then(() => { const server = express() if (dev && devProxy) { devProxy().forEach(function (proxy) { server.use(createProxyMiddleware(proxy.context, proxy)) }) } server.all('*', (req, res) => { return handle(req, res) }) server.listen(port, (err) => { if (err) throw err console.log(`> Ready on http://localhost:${port}`) }) }) .catch((err) => { console.log('An error occurred, unable to start the server') console.log(err) })Copy the code
- Configure the proxy.js file
const proxy = () => {
const testServer = 'https://www.myrds.io/'
return [
{
context: ['/api'],
target: testServer,
secure: false,
changeOrigin: true,
cookieDomainRewrite: {
'*': '',
},
},
]
}
module.exports = proxy
Copy the code
- Modify package.json accordingly