300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 解决angular+spring boot的跨域问题

解决angular+spring boot的跨域问题

时间:2022-01-28 00:16:24

相关推荐

解决angular+spring boot的跨域问题

产生跨域访问的情况主要是因为请求的发起者与请求的接受者1、域名不同;2、端口号不同

下面给出详细步骤:

如果要用到Cookie,那么需要在前端设置.withCredentials=true 在后端写一个配置类CorsConfig,这个类继承WebMvcConfigurerAdapter,在里面进行后台跨域请求配置。 注意:要将$http中的url的地址写完整,例如'http://localhost:8080/getExamsByPage',如果省略http://就无法跨域,因为它代表了协议类型

下面给出相应代码

js中的配置全局$http请求的代码:

var utils = angular.module('ecnuUtils', ['ngCookies', 'ngStorage']);utils.config(['$httpProvider', config]);function config($httpProvider) {$httpProvider.defaults.withCredentials = true;$httpProvider.mon = { 'Access-Control-Allow-Origin' : '*' }}

CorsConfig的代码:

package edu.ecnu.yjsy.conf;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class CorsConfig extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。