Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - Angular2/Spring Boot Allow Cross Origin on PUT

I have a little problem on my web application: an angular2 app connected to a spring boot API.

I can't access my request from the angular2 app. I get this error :

Failed to load http://localhost:8080/deliveryMan/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Java code :

@RestController
@RequestMapping(value = "/deliveryMan")
@CrossOrigin
public class DeliveryManController {

    @Autowired
    DeliveryManService deliveryManService;

    @RequestMapping(value = "/getAllDeliveryMan", method = RequestMethod.GET)
    public Iterable<DeliveryMan> getAllDeliveryMan(){
        return deliveryManService.findAll();
    }

    @RequestMapping(method = RequestMethod.PUT, consumes = "application/json")
    public DeliveryMan addDeliveryMan(@RequestBody DeliveryMan deliveryMan) throws InvalidObjectException {
        deliveryManService.save(deliveryMan);
        return deliveryMan;
    }

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class MyApp{

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

The angular2 code :

private apiUrl = 'http://localhost:8080/deliveryMan/';

getAll(): Promise<DeliveryMan[]> {
  const url = this.apiUrl + 'getAllDeliveryMan';
  return this.http.get(url)
    .toPromise()
    .then(response => response.json().data as DeliveryMan[])
    .catch(this.handleError);
}

saveDeliveryMan(deliveryMan: DeliveryMan): Promise<DeliveryMan> {
  const url = this.apiUrl;
  return this.http.put(url, JSON.stringify(deliveryMan), this.headers)
    .toPromise()
    .then(() => deliveryMan)
    .catch(this.handleError);
}

In order to solve the problem, i added @CrossOrigin to my controller class. It resolves the problem for the getAll method but not for the additional one.

How to resolve it so I can use PUT methods without getting this error?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create CORSFilter.java file in your project.

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    /**
     * CORS filter for http-request and response
     */
    public CORSFilter() {
    }

    /**
     * Do Filter on every http-request.
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access_token, authorization, content-type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    /**
     * Destroy method
     */
    @Override
    public void destroy() {
    }

    /**
     * Initialize CORS filter 
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }
}

You can refer this post Angular 2 Spring Boot Login CORS Problems


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...