Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetch设置headers失效 #277

Closed
xaviertung opened this issue Nov 15, 2016 · 12 comments
Closed

fetch设置headers失效 #277

xaviertung opened this issue Nov 15, 2016 · 12 comments
Labels

Comments

@xaviertung
Copy link

@sorrycc utils/request.js中设置headers,在浏览器查看http请求,发现未在request headers中生效:
request.js代码:

fetch(url, {
    body:"name=%E4%B8%AD%E6%96%87&mobile=121212121&password=111111&captcha=sdsds",
    method:"post",
    mode:"no-cors",
    headers:{
        Accept:"application/json",
        Authorization:"Bearer dfdfdfdfdfdfdf",
        Content-Type:"application/json"}
});

浏览器中Request Headers显示未生效:
accept:application/json
content-type:text/plain;charset=UTF-8

请教一下,如何设置headers头信息呢?比如将token塞进header中?

@sorrycc
Copy link
Member

sorrycc commented Nov 16, 2016

参考 https://www.npmjs.com/package/whatwg-fetch#post-json ,不过你的代码看起来好想也没问题。

@xaviertung
Copy link
Author

OK,谢谢,我再尝试一下。

@lincenying
Copy link

Content-Type 是不是该加个引号包起来.

@huzhengke
Copy link

@xaviertung 该问题你解决了吗,怎么解决的,能否请教下,我折腾了好久还是不行。

@monkindey
Copy link

hi, @huzhengke , @lincenying 的方式应该是正解

@huzhengke
Copy link

@monkindey 加引号,按照官网的写法依然没用呀。

@JayM0826
Copy link

JayM0826 commented Apr 2, 2018

@huzhengke 请问解决了吗?新人又入坑了。。。。

@linonetwo
Copy link

得这样

fetch(
    new Request(`${API}${path}`, {
      headers: new Headers({ Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' }),
    }),
  )
    .then(res => res.json());

关键是用 Request 和 Headers 对象。

@crazylxr
Copy link

@xaviertung 你把 mode 设置为 'cors' 就行了,不要用 'no-cors'

@suedar
Copy link

suedar commented May 14, 2019

请问有解决方法吗

@linonetwo
Copy link

@suedar 你看我那个行不行

@hoipo
Copy link

hoipo commented Jul 17, 2021

跨域的时候还会出现header缺失问题,只能返回部分header头

If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. cors and basic responses are almost identical except that a cors response restricts the headers you can view to Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

10 participants