Angular HttpClient不发送POST,它发送OPTIONS [英] Angular HttpClient doesn't send POST, it sends OPTIONS

查看:272
本文介绍了Angular HttpClient不发送POST,它发送OPTIONS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,使用Angular HttpClient(也写英文)

Im' newbie using Angular HttpClient (and writting english too)

我遇到问题,我正在尝试使用POST方法发送HTTP请求,以便协商OAuth令牌阻塞,但是angular发送OPTIONS请求:

I have a problem, I'm trying sending HTTP request with POST method in order to negociate OAuth token obtenction but angular sends OPTIONS request:

服务:

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);

结果:

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

For my backend, I'm using Spring Security and i added a filter to allow 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;
}

推荐答案

它与角度无关,是您的浏览器在做的.

It is not angular related, it is your browser doing.

检查此问题.

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

I assume your server runs at localhost:8080, and your angular application at localhost:4200. Since, your request is a cross origin request, browser first sends an OPTIONS request to see if it is safe. At this point, your server returns a response with http code 401 which prevents the post request from being made. Either you have to do some config in your server or you can use webpack proxy. This is just for your local machine. If you serve your bundled angular application from your server, then you won’t have to do anything for production. I’ve been using this technique for quite some time, and it works just fine.

示例

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

Users access my angular application from mydomain.com/ng-app I also serve my rest api from same domain, mydomain.com/api

因此,我的应用程序总是向服务器发送请求,从而不会在生产中造成问题.

So my application always make the request to the server it’s being served from which causes no problem in production.

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

For latter, you can do following

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

Create a proxy.conf.json at the root of your project (next to package.json) And put following inside

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

在package.json中,编辑您的start脚本并将其设置为ng serve --proxy-config proxy.conf.json

In package.json, edit your start script and make it ng serve --proxy-config proxy.conf.json

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

Also, from your frontend, do not send the requests to localhost:8080 directly, instead just write something like http.post('/api/getSomeData') which will make the request to localhost:4200 which will redirect it to localhost:8080. This way, you won't have to deal with CORS.

这篇关于Angular HttpClient不发送POST,它发送OPTIONS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆