这是我参与更文挑战的第4天,活动详情查看: 更文挑战
业务场景
前后端分离是目前最为常用的开发流程, 在这个过程中, 除了相互友好的讨论与研究外, 另前端小伙伴最难受的莫过于跨域请求这四个字
本文列举出如下几种处理它的方式:
- Vue devServer.proxy代理配置
- Vue Java 使用Maven进行捆绑打包
- JSONP
- Nginx代理
其中前两种只对指定的技术栈适用, 后两种可用于全部项目
废话不多说, 还是来看看代码吧
方案
Vue devServer.proxy代理配置
使用此方法时, 要注意关闭mock.js
我们需要修改vue.config.js:
const proxy = require('http-proxy-middleware');
const proxy_url = {
server: "http://127.0.0.1:9999"
}
module.exports = {
devServer:{
host: 'localhost',
port: 8001,
proxy:{
'/api':{
target: proxy_url.server,
changeOrigin: true,
ws: true,
pathRewrite: {}
}
}
}
}
具体参数可以参考Github上的http-proxy-middleware文档
简单说明下几个常用参数的含义:
- target(string): 可以理解为设置axios的baseURL, 即请求的根路径
- ws(boolean): 是否代理websocket
- xfwd(boolean): 是否增加x-forward headers
- secure: 是否验证SSL证书
- changeOrigin(boolean): 是否修改请求header中的origin
- pathRewrite(object): 路径重写规则, 内容为对象, 例如{'^/api': '/'}的含义为将
http://localhost:8001/api/test
代理为http://127.0.0.1:9999/test
Vue Java 使用Maven进行捆绑打包
此方法适用于Java项目的生产模式, 主要面对后端小伙伴
首先, 我们将前端代码转换为后端Java项目中的一个module, 编写pom.xml即可:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>koala-ui</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>cn.houtaroy</groupId>
<artifactId>koala-build</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../koala-build</relativePath>
</parent>
</project>
之后, 我们使用exec-maven-plugin插件修改打包命令, pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>exec-npm-install</id>
<phase>prepare-package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>yarn</executable>
<arguments>
<argument>install</argument>
</arguments>
<workingDirectory>${basedir}</workingDirectory>
</configuration>
</execution>
<execution>
<id>exec-npm-run-build</id>
<phase>prepare-package</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>yarn</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
<workingDirectory>${basedir}</workingDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
这里我使用的是yarn, 可以根据实际情况进行修改, arguments标签中的内容也要根据项目实际的package.json编写
上面的实际含义为: maven install时, 在cmd执行yarn run build
还没结束, 最重要却最容易被忽略的一步, 我们需要在vue.config.js中调整前端打包后文件的输出目录:
const vueConfig = {
publicPath: './',
outputDir: 'target/classes/public',
assetsDir: 'static',
// 其它配置
}
module.exports = vueConfig;
现在可以去开心愉快的打包了
JSONP
JSONP需要服务端的支持, 这里不进行赘述, 可以参照这篇文章
Nginx代理
使用Nginx在笔者看来是最完美的解决方案
Nginx对于web服务的支持也非常优异
如何使用Nginx并进行跨域处理, 可以参照我的详细教程使用Nginx处理跨域问题