鍍金池/ 問答/Linux  HTML/ fetch跨域POST報401 Unauthorized

fetch跨域POST報401 Unauthorized

export const login = accesstoken => dispatch => {
  return fetch('https://cnodejs.org/api/v1/accesstoken', {
    method: 'POST',
    body: JSON.stringify({ accesstoken })
  }).then(res => {
    if (res.ok) {
      return res.json()
    } else {
      return Promise.reject(res.statusText)
    }
  }).then(({
    loginname
  }) => Promise.resolve(loginname))
}

如上,用的是瀏覽器原生的Fetch接口,但是由于涉及到跨域POST請求,沒有事先發(fā)送OPTIONS請求,所以直接返回了401,請問有什么比較好的解決方法么?

回答
編輯回答
深記你
export const login = accesstoken => dispatch => {
  return fetch('https://cnodejs.org/api/v1/accesstoken', {
    method: 'POST',
    body: JSON.stringify({ accesstoken }),
    // // 加一句
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  }).then(res => {
    if (res.ok) {
      return res.json()
    } else {
      return Promise.reject(res.statusText)
    }
  }).then(({
    loginname
  }) => Promise.resolve(loginname))
}

沒有發(fā)起OPTIONS請求是因為這所有的一切設(shè)置還無法觸發(fā)preflight request。

2018年4月9日 10:40