Angular HttpClient 不发送 POST,而是发送 OPTIONS

2024-01-01

我是使用 Angular HttpClient 的新手(也写英语)

我有一个问题,我正在尝试使用 POST 方法发送 HTTP 请求,以便协商 OAuth 令牌获取,但 Angular 发送 OPTIONS 请求:

Service:

login(username: string, password: string) {
const body = `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&grant_type=password`;

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic ' + btoa(TOKEN_AUTH_USERNAME + ':' + TOKEN_AUTH_PASSWORD)
  })
};  


return this.http.post<string>(AuthenticationService.AUTH_TOKEN, body, httpOptions);

Result:

对于我的后端,我使用 Spring Security 并添加了一个过滤器以允许 CORS:

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

它与角度无关,这是您的浏览器所做的。

检查这个问题 https://github.com/angular/angular/issues/7445.

我假设您的服务器在 localhost:8080 运行,而您的角度应用程序在 localhost:4200 运行。由于您的请求是跨源请求,浏览器首先发送一个OPTIONS请求查看是否安全。此时,您的服务器返回一个带有 http 代码 401 的响应,这会阻止发出 post 请求。 您必须在服务器中进行一些配置,或者您可以使用 webpack 代理。这仅适用于您的本地计算机。如果您从服务器提供捆绑的角度应用程序,那么您无需为生产做任何事情。我已经使用这种技术有一段时间了,而且效果很好。

Example,

用户从 mydomain.com/ng-app 访问我的角度应用程序 我还从同一域 mydomain.com/api 提供其余 api

因此,我的应用程序总是向为其提供服务的服务器发出请求,这不会在生产中造成问题。

对于后者,您可以执行以下操作

创建一个proxy.conf.json在项目的根目录下(旁边package.json) 并将以下内容放入其中

{
    "/api/": {
        "target": "http://localhost:8080",
        "secure": false,
        "changeOrigin": true
    }
}

在 package.json 中,编辑start编写脚本并制作它ng serve --proxy-config proxy.conf.json

另外,从您的前端,不要直接将请求发送到 localhost:8080,而只需编写类似的内容http.post('/api/getSomeData')这将向 localhost:4200 发出请求,并将其重定向到 localhost:8080。这样,您就不必处理 CORS。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular HttpClient 不发送 POST,而是发送 OPTIONS 的相关文章

随机推荐