const token = localStorage.getItem("blog-key")
const header={Authorization:`Bearer ${token}`}
const res = await http.post('/comment/add', commentParam,header)
请求报跨域错误,它发生在一个网页请求另一个域名下的网页,浏览器出于安全策略,限制了一个网页获取从同一域名下的数据,以防止恶意脚本攻击
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/comment/add");
WebMvcConfigurer.super.addInterceptors(registry);
后端也对请求路径进行拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod))
return true;//访问静态找资源
String token=request.getHeader("authorization");
if (StringUtils.isBlank(token)){
Result result=new Result(400,"请登录",null);
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSON(result));
return false;
此时需要配置后端CORS(跨域资源共享)
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}
上述代码表示允许来自
http://localhost:8080的请求访问以/api开头的所有请求。允许的请求方法为GET、POST、PUT、DELETE,允许的请求头为任意值,允许携带cookie,缓存时间为3600秒。
需要注意的是,上述代码中的addCorsMappings方法是WebMvcConfigurer接口中的一个方法,需要实现该接口并重写该方法。该方法中的CorsRegistry对象用于配置跨域请求的详细参数。在该方法中可以配置允许跨域请求的源、允许的请求方法、允许的请求头等参数。