[英]Unable to hit spring boot Rest API from my angular 5 project
I am preparing a sample application based on Micro-service, where i want to hit my back-end API written in spring boot. 我正在准备一个基于微服务的示例应用程序,我想在该应用程序中找到用Spring Boot编写的后端API。 now i want it to run from my angular 5 UI application. 现在,我希望它从我的angular 5 UI应用程序中运行。
But getting below error. 但是变得低于错误。 i did ctrl+F12 and from the console i got below error. 我做了ctrl + F12,从控制台我得到了以下错误。
Failed to load http://localhost:8080/contacts : No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:8080 / contacts :所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。
You need to allow CORS ( cross-origin resource sharing ) in your spring boot based microservice. 您需要在基于Spring Boot的微服务中允许CORS( 跨域资源共享 )。
This tutorial from Pivotal Team nicely explains how to achieve CORS support in Spring Boot applications: Pivotal团队的本教程很好地解释了如何在Spring Boot应用程序中实现CORS支持:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
If you are using Spring Boot, it is recommended to just declare a WebMvcConfigurer bean as following: 如果您使用的是Spring Boot,建议仅声明一个WebMvcConfigurer bean,如下所示:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
I suggest to use an angular proxy configuration. 我建议使用角度代理配置。
1) Create a new file in the frontend root directory (next to package.json file). 1)在前端根目录(package.json文件旁边)中创建一个新文件。 You can name is file whatever you want, proxy.config.json for example. 您可以随意命名文件,例如proxy.config.json。 This files contains a javascript object. 该文件包含一个javascript对象。
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false
}
}
2) Change the 'ng start' script into package.json to "start": "ng serve --proxy-config proxy.config.json"
2)将“ ng start”脚本更改为package.json以"start": "ng serve --proxy-config proxy.config.json"
3) Restart the cli server (if necessary) 3)重新启动cli服务器(如有必要)
Each calls from your angular-cli server to /api will be redirected to http://localhost:8080/api . 从angular-cli服务器到/ api的每个调用都将重定向到http:// localhost:8080 / api 。 This way, yo don't have to touch the CORS config and will not affect the production security. 这样,您不必触摸CORS配置,也不会影响生产安全性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.