【发布时间】:2019-12-28 15:17:42
【问题描述】:
我的 Spring 应用程序在地址 localhost:8081 上运行 我的前端 Vue.js 在地址 localhost:8080 上运行。
我有 WebMvcConfig:
...
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("*")
.allowedOrigins("http://localhost:8080");
}
}
我在 Vue 组件中有请求
import HTTP from '../api/http-common'
...
HTTP.post('/registration', this.form)
.then(response => {
if (response.data.errors) {
this.errors = response.data.errors
} else {
this.$router.push("/");
}
})
这里是http-common
import axios from 'axios'
export default axios.create({
baseURL: 'http://localhost:8081/api'
})
它以前可以工作,我在WebMvcConfig 下:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/api/registration")
.allowedOrigins("http://localhost:8080");
}
}
然后我必须向地址 localhost:8081/api/activate/{code} 发出请求。 我在“/api/activate/**”上替换了“/api/registration”,但它不起作用。现在这两个设置都不起作用了。
我想允许来自 localhost:8080(我的前端 Vue.js 正在运行的地方)的所有请求
我在浏览器 Chrome 中进行了下一次 CORS 测试:
GENERAL
Request URL: http://localhost:8081/api/registration
Request Method: OPTIONS
Status Code: 403
Remote Address: [::1]:8081
Referrer Policy: no-referrer-when-downgrade
RESPONSE HEADER
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 20
Date: Fri, 23 Aug 2019 09:30:42 GMT
Expires: 0
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
REQUEST HEADER
Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:8080
Referer: http://localhost:8080/registration
Sec-Fetch-Mode: no-cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
来自控制台的错误:
Access to XMLHttpRequest at 'http://localhost:8081/api/registration' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
createError.js?2d83:16 Uncaught (in promise) Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:81)
【问题讨论】:
标签: spring spring-mvc vue.js spring-security cors