没有授权头从Angular发送POST到Spring

时间:2018-06-09 14:36:05

标签: spring angular cors

我有:

  • 使用 Spring
  • 编写的后端服务器
  • Angular
  • 编写的客户端

我正在尝试发送POST请求...

<script>
	  var homework= document.getElementById("homerwork");
	  var teeth= document.getElementById("teeth");
	  var reading= document.getElementById("reading");
	  var stuff= document.getElementById("stuff");
	  var good= document.getElementById("good");
	


		homework.addEventListener("click", rightclick);
		teehth.addEventListener("click",righclick);
		reading.addEventListener("click", righclick);
		stuff.addEventListener("click", righclick);
		good.addEventListener("click", rigclick);

	function rightclicks () {
	
	

	//function that will trigger the animation//
		
		
		}

</script>

使用Wireshark过滤请求我得到了:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class AuthenticationService {
  constructor(private http: HttpClient) { }

  login(username: string, password: string) {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type' : 'application/x-www-form-urlencoded',
        'Accept' : 'application/json',
        'Authorization' : 'Basic blablabla_base64_encoded'
      })
    };

    const body = 'username=' + username + '&password=' + password + '&grant_type=password';

    console.log(body);
    console.log(httpOptions.headers);
    console.log(this.http.post<any>('http://localhost:8080/oauth/token', body, httpOptions));

    return this.http.post<any>('http://localhost:8080/oauth/token', body, httpOptions)
      .map(
      user => {
        // login successful if there's a jwt token in the response
        if (user && user.token) {
          // store user details and jwt token in local storage to keep user logged in between page refreshes
          localStorage.setItem('currentUser', JSON.stringify(user));
        }

        return user;
      });
  }

  logout() {
    // remove user from local storage to log user out
    localStorage.removeItem('currentUser');
  }
}

由于某种原因,我没有授权标题,我的POST请求变为OPTIONS。我在网上搜索了一些小时的其他解决方案,但没有一个能帮助我。

一些建议?

1 个答案:

答案 0 :(得分:0)

找到这个问题的答案。

Spring服务器必须根据此处文档中解释的范例管理预先发出的请求: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

要添加CORS管理,可以在Spring Boot App中实现的所有其他过滤器之前添加CORSFilter,这里有一个很好的代码示例: https://gist.github.com/malike/f8a98b498368932e6d7511886a167848