首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 5 Http Post请求

Angular 5 Http Post请求
EN

Stack Overflow用户
提问于 2018-04-28 03:22:39
回答 2查看 2.2K关注 0票数 1

我正在尝试通过Webstorm使用Angular 5构建一个应用程序。我已经在后端设置了我的服务。当我尝试从postman或Rest客户端工具检索数据时,Webstorm提供的一切都是正常的。

但是当我试图从我的实际代码中获取数据时,angular说

代码语言:javascript
复制
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 

我在我的java服务的后端添加了头文件,比如

代码语言:javascript
复制
        response.addHeader("Access-Control-Allow-Origin", "*"); 
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

我在出口课上的作用如下

代码语言:javascript
复制
      constructor(private http: HttpClient) { }




  login(username: string, password: string) {
    console.log(username + '' + password);
    const headers = new HttpHeaders().append('Content-Type', 'application/json')
    const url  = 'http://localhost:8080/../UserLogin';



    return this.http.post(url, {'username': username, 'password': password}  )
      .subscribe(
      (data: any) => {
        console.log(data);

      }
    );

  }

当我检查来自chrome的Network Session的请求头时,我看到请求方法是options,并且没有请求数据。

我有点困惑为什么postman和webstrom的rest客户端运行得很好,而不是我的函数,第二个客户端是关于从Post转换为OPTIONS的请求方法

任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2018-04-28 03:29:41

您需要添加{ withCredentials: true }作为帖子的第三个参数。

代码语言:javascript
复制
return this.http.post(
    url,
    {'username': username, 'password': password},
    { withCredentials: true }
  )
  .subscribe(
    (data: any) => {
      console.log(data);
    }
  );
票数 1
EN

Stack Overflow用户

发布于 2018-04-28 04:09:57

实际问题取决于Chrome如何评估CORS操作。

我从一个相对的帖子中找到了这个答案,这对我真的很有帮助

No 'Access-Control-Allow-Origin' header is present on the requested resource error

如果您安装了该扩展,一切都会恢复正常:

Chrome Extension

扩展的3小时浪费:P

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50069033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档