Grunt在浏览器中连接CORS错误

时间:2016-04-07 09:40:17

标签: cors grunt-contrib-connect

我正在尝试将一个小角度应用程序连接到我在春天写的其余web服务。我的tomcat服务器在localhost:8080上运行,我的grunt服务器在localhost:11000上运行。这会导致控制台中的CORS错误,我无法从浏览器向其他API发出请求。

我整个上午花了很多时间在网上找到我发现的帖子,但我仍然无法使用它,我现在能够将我的页面提供给我,因为一些例子甚至可以阻止它工作。我确实看到grunt服务器写入的cmd窗口中的控制台日志记录,但无论我尝试了什么,我只是不断收到CORS错误:

  connect: {
            livereload: {
                options: {
                  port: 11000,
                  hostname: 'localhost',
                  open: false,                                     
                  middleware: function(connect, options, middlewares) {                       
                        middlewares.unshift(function(req, res, next) {
                            console.log('***** ADDING HEADERS *****');
                            res.setHeader('Access-Control-Allow-Origin', '*');
                            res.setHeader('Access-Control-Allow-Credentials', true);
                            res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                            res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
                            next();
                        });

                        return middlewares;
                    }                                    
               }        
            } 
        } 

有人能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

Ok so it looks like the grunt config above does actually work. I had to make some amendments in spring to get this working.

I have never had to do this before as usually the requests to the back end API are sent from java and the front end app is also written in java and the requests go from browser >> tomcat\spring\java and then if this app needs to make rest calls to the backend it is then initiated from java which doesnt cause these issues.

Anyway here is an example of the fix for anyone that may get this issue when trying to call rest API's written in spring directly from an angular app running in a different container.

Configure the following in your configuration classes:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/calculator/*").allowedOrigins("http://localhost:11000");
        }
    };
}

This is also only for development and not wanting to have to deploy to apache webserver as I could probably have fixed this quite easily using http proxying, doing this means when I run my selenium tests I will be able to start the grunt server and deploy the angular app to that and still run all my integration tests during my automated build process.

相关问题