我正在尝试通过angular.js 4向java rest api发送请求。我收到以下错误:NO' Access-control-allow-origin'标头出现在请求的资源上。因此,不允许原始http://localhost:4200访问 我的代码如下:
signupUser() {
// if (this.signupForm.dirty && this.signupForm.valid) {
// let headers = new Headers({ 'Content-Type': 'application/json' });
let data = {
"email": this.signupForm.value.email,
"password": this.signupForm.value.password,
'phone': this.signupForm.value.mobile,
// 'first_name': 'dd1',
// 'email': 'xyz@gmail.com',
// 'password': 'manju',
// 'phone': '123456',
'signup_type': 'Custom',
// social_media:
// "email": this.loginForm.value.name,
// "password": this.loginForm.value.password
};
console.log(data)
let options = {
type: "GET",
url: "http://localhost:8085/dashboard/signUp",
body: JSON.stringify(data)
};
this.http.post(options.url, options.body, {
headers: this.headers
}).subscribe((data) => {
console.log(data);
this.otpScreen = true;
}, (err) => {
console.log(err);
});
// alert(`Name: ${this.userForm.value.name} Email: ${this.userForm.value.password}`);
// }
}
@CrossOrigin(origins="http://localhost:4200")
在java代码中添加这一行必须解决这个问题,但仍然有同样的错误,任何人都可以告诉我如何解决这个问题?我的控制器看起来像:
@CrossOrigin
@RequestMapping("/signUp")
public void getOTP(HttpServletRequest request, HttpServletResponse response){
System.out.println("In Signup");
}
答案 0 :(得分:0)
只需将扩展名Allow-Control-Allow-Origin:* 1.0.3添加到Chrome浏览器即可。 然后在地址栏旁边会出现一个CORS按钮,只需启用它并在chrome上运行你的项目它就能正常工作。 Link for Allow-Control-Allow-Origin extension
答案 1 :(得分:0)
或向spring应用程序添加全局配置,允许localhost:4200
e.g。
package nl.ivonet.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* Adds a CORS filter on http://localhost:4200 allowing it cross origin access.
* It is the url where ng serve works when developing.
* <p>
* you could also add @CrossOrigin(origins = "*") to the rest method but this is global.
*
* @author Ivo Woltring
*/
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}