如何使用springboot允许access-controll-allow-origin

时间:2017-04-19 12:54:05

标签: angularjs tomcat spring-boot

我在前端使用angularjs,我试图到达一个远程服务器(tomcat),该服务器是在我项目的后端使用springboot实现的。

但是我遇到了这个错误:

对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://localhost:8080'因此不允许访问。响应的HTTP状态代码为403。

我试图解决这个问题,仍然有相同的问题。

这是前端代码:

var services = angular.module(' TestService',[]);

services.factory(' TestService',[' $ http',' $ q',功能($ http,$ q){

var factory = {
        add: add
    };

    return factory;

    function add(body) {
        var deferred = $q.defer();
        var headers = {
                'Access-Control-Allow-Origin':'*',
                'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            };

            $http({
                headers: headers,
                method: 'POST',
                url: 'http://localhost:8081/test/add',
                dataType: 'json',

                data: body
            })
            .then(function(response) {
                deferred.resolve(response.data);
                console.log('Service works');
                console.log(response.data);
            }, function(errResponse) {
                console.log("erreur");
                deferred.reject(errResponse);
            });
        return deferred.promise;
    }
}]);

这是我的后端代码:

import java.io.IOException;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import fr.edf.sdin.mrs.recherche.model.entities.ResultEntity;
import fr.edf.sdin.mrs.recherche.service.TestService;

@RestController
@RequestMapping("/test")
@CrossOrigin(origins="*",maxAge=3600, methods={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.OPTIONS,RequestMethod.DELETE}, allowedHeaders={"x-requested-with", "accept", "authorization", "content-type"}, 
exposedHeaders={"access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options"},allowCredentials="false",value="/test")
public class TestController{

    @Autowired 
    TestService service;
        @PostMapping(value = "/add", produces = "application/json")
    public ResponseEntity<ResultEntity<String>> add (@RequestBody String body, HttpServletResponse response) throws IOException {
        //LOGGER.info("Entree dans le controller back");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        System.out.println(body);
        String result = service.add(body);
        System.out.println(result);
        if (result.equals("")) {
            new ResponseEntity<String>("KO", HttpStatus.OK);
        }
        return new ResponseEntity<ResultEntity<String>>(new ResultEntity<String>(result), HttpStatus.OK);
    }


    @GetMapping(value = "/add", produces = "application/json")
    public ResponseEntity<?> delete (@RequestBody String body, HttpServletResponse response) throws IOException {
        //LOGGER.info("Entree dans le controller back");
        response.setHeader("Access-Control-Allow-Origin", "*");
         response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        System.out.println(body);
        String result = service.add(body);
        if (result.equals("")) {
            new ResponseEntity<String>("KO", HttpStatus.OK);
        }
        return new ResponseEntity<String>(result, HttpStatus.OK);
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

时会发生此错误
  1. 服务器不允许跨域标头。
  2. 应用程序不允许跨域标头。
  3. 应用程序不接受请求提供的自定义标头。
  4. Refer