最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Response for preflight has invalid HTTP status code: 401 angular - Stack Overflow

programmeradmin3浏览0评论

Using angular and Spring Boot we're trying to add authentication to our service but for some reason we can't 'open' and fetch data from an url we know works

Angular:

this.getMismatches = function () {
    return $http({
            "async": true,
            "crossDomain": true,
            "url": GLOBALS.mismatchUrl,
            "method": "GET",
            "headers": {
                "authorization": "Basic YWRtaW46USNROawdNmY3UWhxQDlQA1VoKzU="
        }
    });
}

(currently the login token is hard coded for testing purposes)

Rest service:

@CrossOrigin(origins = "*")
@RequestMapping("/api/mismatch")
public List<Mismatch> home() {
    return service.getAll();
}

CrossOrigin = * should take care of the CORS issue but this failed URL call is really weird.

Extra things we've tried:

'Access-Control-Allow-Methods', 'GET, POST, OPTIONS'
'Access-Control-Allow-Origin', '*'
'Content-Type', json plaintext jsonp etc

App.js:
    $httpProvider.defaults.headersmon = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};

Using angular and Spring Boot we're trying to add authentication to our service but for some reason we can't 'open' and fetch data from an url we know works

Angular:

this.getMismatches = function () {
    return $http({
            "async": true,
            "crossDomain": true,
            "url": GLOBALS.mismatchUrl,
            "method": "GET",
            "headers": {
                "authorization": "Basic YWRtaW46USNROawdNmY3UWhxQDlQA1VoKzU="
        }
    });
}

(currently the login token is hard coded for testing purposes)

Rest service:

@CrossOrigin(origins = "*")
@RequestMapping("/api/mismatch")
public List<Mismatch> home() {
    return service.getAll();
}

CrossOrigin = * should take care of the CORS issue but this failed URL call is really weird.

Extra things we've tried:

'Access-Control-Allow-Methods', 'GET, POST, OPTIONS'
'Access-Control-Allow-Origin', '*'
'Content-Type', json plaintext jsonp etc

App.js:
    $httpProvider.defaults.headers.mon = {};
    $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.put = {};
    $httpProvider.defaults.headers.patch = {};
Share Improve this question edited Jan 30, 2018 at 17:28 DGK asked Feb 14, 2017 at 8:53 DGKDGK 3,0155 gold badges33 silver badges51 bronze badges 6
  • What's GLOBALS.mismatchUrl set to? I'd imagine it doesn't say "Invalid URL" for no reason at all... – Brother Woodrow Commented Feb 14, 2017 at 8:56
  • My bad, posted the wrong error message. – DGK Commented Feb 14, 2017 at 9:00
  • can you get response in postman? – bipin patel Commented Feb 14, 2017 at 9:04
  • Yeah, that's the weird part. – DGK Commented Feb 14, 2017 at 9:05
  • can you give 'GLOBALS.mismatchUrl' value? – bipin patel Commented Feb 14, 2017 at 9:13
 |  Show 1 more ment

1 Answer 1

Reset to default 12

You have mentioned in your ments that by using postman you can get the response as expected. That is a good starting point. I suspect that by using the curl mand curl -i -X URL from the terminal also returns the correct response.

If postman works correctly, you have to be aware by the fact that right before making a request angular sends another request, called pre-flight request, which does a minimal check to the endpoint at the server side.

This request is an OPTIONS type request.

First, you have to make sure that your dispatcherServlet accepts OPTIONS requests. You can achieve this either by specifying it in a *.properties configuration file , such as:

spring.mvc.dispatch-options-request=true

or by configuring web.xml

<servlet>
    <!--content eluded for clarity-->
    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

After you have configured it to accept OPTIONS requests, create a Filter.java and configure a CORS filter.

You can guide by the following example:

public class CorsFilter implements Filter{

@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain filterChain) throws IOException, ServletException {

    if(response instanceof HttpServletResponse){
        HttpServletResponse alteredResponse = ((HttpServletResponse)response);
        addCorsHeader(alteredResponse);
    }

    filterChain.doFilter(request, response);
}

private void addCorsHeader(HttpServletResponse response){
    //TODO: externalize the Allow-Origin
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
    response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");
}

@Override
public void destroy() {}

@Override
public void init(FilterConfig filterConfig)throws ServletException{}
}

In the end, don't forget to add this filter in web.xml along with the following init-params.

<filter>
    <filter-name>cors-filter</filter-name>
    <filter-class>ai.surge.usrmngmtservice.util.cors.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,OPTIONS,PUT</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <!--<init-param>-->
        <!--<param-name>cors.preflight.maxage</param-name>-->
        <!--<param-value>1800</param-value>-->
    <!--</init-param>-->
</filter>

You should be ready to go now.

发布评论

评论列表(0)

  1. 暂无评论