在本地开发时,我们经常会碰到跨域请求问题。我们都知道造成跨域的原因就这么几个: 发起请求的域名、协议或端口不一致时,就会发生跨域行为。
那么如果要在本地开发进行跨域请求呢?我们都是需要后端处理?不需要的,我们只需要进行一个本地服务转发请求就行。下面就讲解两种本地开发配置跨域 和 一种生产环境配置跨域的方式。
(1)Vite的跨域配置
我们使用vue开发时,常用Vite打包。而Vite的跨域配置跨域使用server对象下的proxy属性。其server.proxy的类型是Record<string, string | ProxyOptions>,proxy属性是一个key / value的对象。
如果你的key的值以 ^ 开头,会被自动识别为 RegExp正则匹配的方式。
如我们需要对/api/v2相关的请求路径进行跨域代理到https://juejin.cn, 可以这么配置:
import { defineConfig } from "vite";
export default defineConfig({
server: {
port: 443, // 可以指定端口
proxy: {
'^/api/v2': {
target: 'https://juejin.cn', // 需要代理的目标 host
changeOrigin: true,
rewrite: (path) => path.replace(/^\/post/, ''), // 重写匹配到路径
},
},
},
})
(2)webpack的跨域配置
使用webpack本地开发时,我们可以使用devServer的功能。devServer同样也有proxy的属性,也可以用key / value 的方式进行配置。
以上面同样的例子,对/api/v2进行代理到https://juejin.cn的请求
module.exports = {
//...
devServer: {
proxy: {
'/api/v2': {
changeOrigin: true,
target: 'https://juejin.cn',
pathRewrite: { '^/api/v2': '/post' },
},
},
},
};
如果有多个请求路径都需要代理到同一个目标的请求可以用context进行配置。
module.exports = {
//...
devServer: {
proxy: [
{
context: ['/api/v2', '/get/v1'],
changeOrigin: true,
target: 'https://juejin.cn',
pathRewrite: { // 同时也支持多个配置重写路径
"^/api/v2": "post",
"^/get/v1": "user",
},
},
],
},
};
(3)生产环境的配置
如果想在生产环境也生效我们的跨域配置,那么就需要配置Nginx的服务代理了。我们只需要在proxy.conf下配置server对象的路径映射。
找到Nginx的配置文件,配置其server对象的location, 以上面的例子,继续进行简单的配置
//....
server {
listen 80;
server_name localhost;
location ^~ /api/v2/ {
proxy_pass https://juejin.cn/post;
}
}