简体   繁体   中英

Angular - Maven/Spring Boot CORS not working

I'm am trying to set up an application that has an Angular front-end and a Maven/Spring Boot backend and have set up my first REST controller. My issue is that when I send a GET HTTP request to the backend from my Angular IDE it returns an error stating:

"Access to XMLHttpRequest at ' http://localhost:8080/api/getData ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I'm confused as I have set up the "doFilter" to accept all requests from any origin so it shouldn't be throwing this error. My code follows:

My APIController:

package com.SSCCoursework.controller;

import com.SSCCoursework.Model.SharePrice;
import com.SSCCoursework.Model.Shares;
import com.SSCCoursework.Model.SharesList;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin (origins = "http://localhost:4200", maxAge = 3600)
@RestController
public class ApiController
{ 
    File Shares_File = new File("Shares_Data.xml");
    ArrayList<Shares> shareList = new ArrayList<Shares>();

    @RequestMapping(value="/api/getData", produces="application/JSON")
    public Object getData()
    {   
        Shares share1 = new Shares();
        SharePrice share1_2 = new SharePrice();
        share1.setCompanyName("test");
        share1.setCompanySymbol("test");
        share1.setNumOfShares(123);
        Date date = new Date();
        share1.setLastShareUpdate(date);
        share1_2.setCurrency("dollar");
        share1_2.setValue(12345f);
        share1.setSharePrice(share1_2);
        shareList.add(share1);

        SharesList sharelist = new SharesList();
        sharelist.setBookList(shareList);

        return share1;
    }
}

My SimpleCORSFilter:

package com.SSCCoursework.Security;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter 
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException 
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException 
    {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, Connection, User-Agent, authorization, sw-useragent, sw-version");

        if (req.getMethod().equals("OPTIONS")) 
        {
            res.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() 
    {

    }
}

My Angular code is just trying to use a GET method (this.httpClient.get(' http://localhost:8080/api/getData ') to print the data to the browser console but the error is preventing it from working. Am I missing a step in my backend?

you can easily define a global cors config just by adding in your main application class where you start your spring boot app

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
       registry.addMapping("/**").allowedOrigins("http://localhost:8080")
                      .allowedMethods("PUT", "DELETE", "GET", "POST");
      }
    };
  }

for more details take a look here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM