No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:0000' is therefore not allowed access.
原因:瀏覽器的同源策略不允許跨域訪問,所謂同源策略指協議、域名、端口號相同。
解決方式:局部配置、全局配置、採用proxyTable解決。
第一種——局部配置
在每個controller類的上面添加以下代碼
@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
public class ModelController {
}
第二種——全局配置
在web層的spring.xml配置文件中添加下面代碼
<mvc:cors>
<mvc:mapping path="/**" allowed-origins="*" allow-credentials="true" max-age="1800" allowed-methods="GET,POST,OPTIONS"/>
</mvc:cors>
第三種——採用proxyTable解決
proxyTable是什麼?
vue-cli提供的解決vue開發環境下跨域問題的方法,proxyTable的底層使用了http-proxymiddleware(https://github.com/chimurai/http-proxy-middleware),它是http代理中間件,它依賴node.js, 基本原理是用服務端代理解決瀏覽器跨域:
修改前端的全局配置js文件:
'/api/cms': {
target: 'http://localhost:0000',
pathRewrite: {
'^/api': ''//實際請求去掉/api
}
}