这里再说一下跨域的概念吧。
在Web开发中,浏览器限制了从一个不同来源(协议、域名或者端口) 获取资源的访问。
当在一个页面中通过 Ajax 或者 JavaScript 访问其他域名下的资源时,就会产生跨域问题。
举些例子:
http://example.com | https://example.com 域名相同,但协议不同(http 和 https)http://example.com | http://example.com:8080 域名相同,但端口号不同http://example.com | http://test.example.com 主机名(子域)不同https://example.com | https://anotherdomain.com 域名不同file://localhost/index.html | http://example.com 文件协议和HTTP协议之间的跨域在开发过程中,我们可以通过代理相关的配置,来使得我们可以正常开发。
create-react-app
// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://api.example.com',
changeOrigin: true,
})
);
};
vite
// vite.config.js
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://api.example.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, ''),
},
},
},
};
umi
// .umirc.js
export default {
proxy: {
"/api": {
target: "http://api.example.com",
changeOrigin: true,
pathRewrite: { "^/api": "" },
},
},
};
post("/api/getList");符合/api我要把他拦下来targer:http://api.example.com,还需要rewrite把/api删掉,那我实际的请求就是http://api.example.com/getListpost("/api/getList")了。他请求的是http://localhost/api/getList,他不存在跨域问题。其实就是node端(服务器端)去请求拿到了response,然后把返回结果塞给了我们写的请求。
另外只要返回的结果告诉浏览器,请求我的网址没关系,你别拦,我的内容给他就行。也不会产生跨域问题。

https://baike.baidu.com/里请求了https://miao.baidu.com/abdr。返回的内容(Response Header)告诉浏览器:允许https://baike.baidu.com/访问我(Access-Control-Allow-Origin),你不用拦。