Preface
We always encounter errors like this in projects:
when we are still a novice, we will always immediately search for what the error is. When we encounter more problems, when we see such an error, we will immediately know what the error is. Cross-domain issues,
cross-domain issues: A common question. For a long time, I thought there was nothing to write about such a basic issue. But when I was looking for a job, I found that many interviewers liked to ask, what is cross-domain. Because there is no in-depth understanding of this issue. The answer was disrespectful. Taking this opportunity, I decided to understand cross-domain issues from the bottom up and record them for review later.
很多时候都是第一时间去查询一个问题得解决办法,并不会第一时间去弄清除为啥会引发这个问题
What is cross-domain
跨域全称为Cross-Origin Resource Sharing,意为跨域资源共享,是一种允许当前域下进行资源被其他域资源脚本访问得机制。
However, the browser does not support such cross-domain requests because it violates the browser's same-origin security policy.
跨域并不是请求没有发送出去,服务器收到请求并且返回数据,只有被浏览器拦截了返回结果
Same origin security policy
Before understanding cross-domain, let’s first figure out what the same-origin security policy is.
同源是指协议、域名、端口三者相同
是一种重要得安全策略,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到XSS、CSRF等攻击
Only when the protocol (protocol), domain (domain name), and port (port) are consistent, it is of the same origin.
The browser's security origin policy causes cross-domain error reporting for requests
How to solve cross-domain issues
Backend configuration cross-domain resource sharing: CORS
CORS 全称是 Cross-origin resource sharing 跨域资源共享,CORS 的实现关键在于后端
The main configuration of "Access-Control-Allow-Origin"
is whether the browser enables the same-origin security policy or not, which is determined based on the Access-Control-Allow-Origin response header of the backend interface.
Backend configuration Access-Control-Allow-Origin response header is the most commonly used and most direct method during the development process.
res.header('Access-Control-Allow-Origin', '*')
Configure proxy
Before introducing this, let’s talk about forward proxy and reverse proxy.
Forward proxy
A proxy between the client and the original data service. The client sends a request to the proxy target, and the proxy target sends the request to the target service. The process in which the server returns results to the client. Only the client can use the forward proxy.
Reverse proxy
: The client sends a request and first reaches the proxy service. The proxy service sends the request to the target service. The target service responds to the request and returns the result to the proxy service. The proxy service returns the result to the requesting client.
forward proxy | reverse proxy |
---|---|
proxy client | proxy server |
Hide the real client, the real client is not visible to the server | Hide the real server, the real server is not visible to the client |
Resolve access restriction issues | Provide load balancing, security protection, and data caching |
nginx reverse proxy
proxy_pass is mainly used in nginx proxy configuration, and its usage is flexible and diverse;
simple proxy
server {
listen 80;
listen [::]:80;
listen 443 ssl;
server_name localhost;
location / {
proxy_pass http://127.0.0.10:8080;
}
}
Use upstream method proxy
upstream test {
server: 192.168.0.13:8989;
}
server {
listen 80;
listen [::]:80;
listen 443 ssl;
server_name localhost;
location / {
proxy_pass http://test;
}
}
When configuring proxy_pass proxy forwarding in nginx, if you add / to the URL after proxy_pass, it means the absolute root path; if there is no /, it means a relative path, and the matching path part is also given to the proxy.
node middleware forward proxy
The same-origin policy is only useful for requests sent by the browser, and access to the corresponding service is not restricted.
We can use proxy services to solve cross-domain problems. There are several main steps:
- Accept client requests.
- Forward the request to the server.
- Get the server response data.
- Forward the response to the client.
Front-end configuration agent
vue cli configure forward proxy
The webpack-dev-server development server provided by vue cli supports setting a proxy. You can configure the proxy configuration item under the devServer configuration item in the vue.config.js file to forward the proxy request for the /api path to the real back-end server path. , and then rewrite the forwarded URL as needed.
module.exports = {
devServer: {
port: ‘8090,
open: false,
overlay: {
warnings: false,
errors: true,
},
proxy: {
'/pms': {
target: 'http://192.168.3.11:86',
changeOrigin: true,
pathRewrite: {
'^/zhihuitouzi/qqpt-apply/pms': '/pms',
},
}
},
}
react configure proxy
Create a setupProxy file in the project directory. The corresponding file cannot be found using the scaffolding tool.
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
proxy('/test/api', {
target: 'http://localhost:8000',
changeOrigin: true, // 默认值是false
pathRewrite: {
'^/api1': '' }
}),
proxy('/demmo/api', {
target: 'http://localhost:5001',
changeOrigin: true, // 默认值是false
pathRewrite: {
'^/api2': '' }
}),
)
}
JSONP
JSONP 的原理是利用 <script> 标签的 src 属性允许跨域加载资源,来与服务器进行数据传输。
However, JSONP requires back-end cooperation to achieve the final cross-domain request.
Specific implementation process:
- Declare a callback function, whose function name is passed as a parameter value to the server that requests cross-domain data. The function parameter is the target data to be obtained, that is, the data returned by the server.
- Create a script tag, assign the cross-domain API data interface to the src attribute, and add the function name through question marks. For example?callback=getDatas
- After the server receives the request, it concatenates the passed function name and the data it requires into a string in the form of a function call.
- Finally, the server returns to the client through the HTTP protocol and parses the execution function.
This method only supports get requests, and
is commonly used for some fixed third-party interfaces; it is rarely used in daily development;