Angular在请求标头上未发送正确的标头。

huangapple go评论61阅读模式
英文:

angular not sending correct header on request headers

问题

我正在使用Angular,试图学习一些内容,但无法使用令牌进行简单的Get请求。我进行了很多研究,但最终都得到了这段代码。

对于我的后端,我正在使用Kotlin / Springboot,并已配置了CORS。

尽管如此,当尝试进行此请求时,我收到以下错误信息。

export class AccountService {
    
  endpoint = 'http://localhost:5000/api-v1/account/list'

  constructor(private http: HttpClient) { }

  list() {
    const token = sessionStorage.getItem('token') // 我正确获取到了令牌

    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Headers': '*',
      'Authorization': token,
    }
    
    return this.http.get<any[]>(this.endpoint, { headers: headers })   
  } 
}
跨源资源共享(CORS)策略阻止了从 'http://localhost:4200' 源访问 'http://localhost:5000/api-v1/account/list' 的 XMLHttpRequest。预检请求的响应未通过访问控制检查:所请求资源上未包含 'Access-Control-Allow-Origin' 头。

--

core.js:15713 错误
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "未知错误", url: "http://localhost:5000/api-v1/account/list", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
status: 0
statusText: "未知错误"
url: "http://localhost:5000/api-v1/account/list"
ok: false
name: "HttpErrorResponse"
message: "访问 'http://localhost:5000/api-v1/account/list' 时出现 Http 失败响应:0 未知错误"
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
__proto__: HttpResponseBase

我的服务器端CORS配置如下:

class CorsFilter : Filter {
    override fun init(p0: FilterConfig?) { TODO("not implemented") }

    override fun destroy() { TODO("not implemented") }

    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        val response = servletResponse as HttpServletResponse
        val request = servletRequest as HttpServletRequest

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200")
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS")
        response.setHeader("Access-Control-Allow-Headers", "Content-Type")
        response.setHeader("Access-Control-Allow-Credentials", true.toString())

        if ("OPTIONS".equals(request.method, ignoreCase = true)) {
            response.status = HttpServletResponse.SC_OK
        } else {
            filterChain.doFilter(servletRequest, servletResponse)
        }
    }
}

我真的不知道在Angular中是否需要添加其他内容。

  • Angular CLI: 7.3.1
  • Node: 12.13.0
  • Angular: 7.2.4
英文:

I'm new using angular, I'm trying to learn a little and I can't do a simple Get using a token. I researched a lot and always end up in this piece of code.

For my backend I am using a Kotlin / Springboot and have Cors configured.

Even so when trying to do this REQUEST I get this error.

export class AccountService {

  endpoint = &#39;http://localhost:5000/api-v1/account/list&#39;

  constructor(private http: HttpClient) { }

  list() {
    const token = sessionStorage.getItem(&#39;token&#39;) // I&#39;m getting the token correctly

    const headers = {
      &#39;Content-Type&#39;: &#39;application/json&#39;,
      &#39;Accept&#39;: &#39;application/json&#39;,
      &#39;Access-Control-Allow-Headers&#39;: &#39;*&#39;,
      &#39;Authorization&#39;: token,
    }
    
    return this.http.get&lt;any[]&gt;(this.endpoint, { headers: headers })   } }

> Access to XMLHttpRequest at 'http://localhost:5000/api-v1/account/list' from origin >'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass > access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

--

> core.js:15713 ERROR
> HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: > "http://localhost:5000/api-v1/account/list", ok: false, …}
> headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
> status: 0
> statusText: "Unknown Error"
> url: "http://localhost:5000/api-v1/account/list"
> ok: false
> name: "HttpErrorResponse"
> message: "Http failure response for http://localhost:5000/api-v1/account/list: 0 Unknown Error"
> error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", > …}
proto: HttpResponseBase

my Cors configuration in my server side

class CorsFilter : Filter {
    override fun init(p0: FilterConfig?) { TODO(&quot;not implemented&quot;) }

    override fun destroy() { TODO(&quot;not implemented&quot;) }

    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        val response = servletResponse as HttpServletResponse
        val request = servletRequest as HttpServletRequest

        response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;http://localhost:4200&quot;)
        response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;GET,POST,DELETE,PUT,OPTIONS&quot;)
        response.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;Content-Type&quot;)
        response.setHeader(&quot;Access-Control-Allow-Credentials&quot;, true.toString())

        if (&quot;OPTIONS&quot;.equals(request.method, ignoreCase = true)) {
            response.status = HttpServletResponse.SC_OK
        } else {
            filterChain.doFilter(servletRequest, servletResponse)
        }
    }
}

I really don't know if in Angular we should add anything else.

  • Angular CLI: 7.3.1
  • Node: 12.13.0
  • Angular: 7.2.4

答案1

得分: 0

在你的服务器端代码中,你可以将这一行更改为:

response.setHeader("Access-Control-Allow-Origin", "*")

这应该可以工作。

英文:

On your server side code can you change this line

   response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;http://localhost:4200&quot;)

to

    response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;)

that should work.

huangapple
  • 本文由 发表于 2020年1月6日 18:37:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定