I won't say much about cross-domain related knowledge, and here I will directly talk about the solution. Because what I am accessing here is a file, such as pdf, so I don’t use the java interface. If I use the interface, I can configure it directly at the interface level to allow cross-domain, as follows:
@RestController
@CrossOrigin
public class MyController {
@RequestMapping("/ok")
public Map<String, String> ok() {
Map<String, String> res = new HashMap<>(3);
res.put("name","zhaopq");
res.put("age","18");
res.put("city","天津");
return res;
}
}
What I'm talking about here is not going to the interface level,
1. It is to configure cross-domain access directly at the tomcat level, open the conf/web.xml file in the tomcat installation file, and add the following code:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
In this way, the problem of cross-domain access to tomcat files is solved
2. Use node to build an intermediate gateway layer, use node server to access resources and then return to the front end, cross-domain problems are solved in node, in fact, the principle is the same, create a new node project, the code is as follows:
yarn init
yarn add express
yarn add http-proxy-middleware
然后在package.json加上
"scripts":{
"dev":"node src/index.mjs"
}
新建src目录,下面新建index.mjs文件,.mjs就是一种js文件格式,Node.js 会将.cjs文件视为 CommonJS 模块,将.mjs文件视为 ECMAScript 模块。它会将.js文件视为项目的默认模块系统(除非package.json说的是 CommonJS "type": "module")
import express from 'express'
import { createProxyMiddleware } from 'http-proxy-middleware';
const app = express();
//这里解决跨域问题
app.all('*', (_, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Content-Type')
res.header('Access-Control-Allow-Methods', '*')
next()
})
// --------- 这里设置个代理访问,跟vue里面devServer的代理差不多 -------------------------
app.use('/proxy', createProxyMiddleware({
target: "http://paperless-ftp.example.com",
changeOrigin: true,
pathRewrite: {
"^/proxy": ""
}
}))
app.listen(3002, () => console.log('Server is running on port 3002'))
For example, the access file path is http://paperless-ftp.example.com/test.pdf , now change it to http://localhost:3002/proxy/test.pdf
If it is a development environment, just configure devServer directly in vue.config.js, as follows:
proxy: { // 配置跨域
'/proxy': {
target: 'http://paperless-ftp.example.com',
changOrigin: true, // 允许跨域
pathRewrite: {
'^/proxy': ''
}
}
}
Same as above, for example, the access file path is http://paperless-ftp.example.com/test.pdf , now change it to http://localhost:port number/proxy/test.pdf
Finished manual work! !