网站搜索

javascript - 使用 isomorphic-fetch 进行基本身份验证


我想使用 isomorphic-fetch 发送一个带有一些凭证的 POST 请求。这是我目前的代码:

export default function fetchJson(url: string, options: any) {
  options.headers = (<any>Object).assign({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }, options.headers);
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON);
}

export function fetchLogs(dispatch_ok: any, dispatch_error: any) {
      var URL = "http://server_address:8080/api/getlogs/";
      return fetchJson(URL, {
                       method: 'get',
                       credentials: 'include',
                       headers: {
                            Authorization: 'Basic '+window.btoa('user:passwd'),
                       }
             }).then((data: any) => {
                 if (data.results.length != 0) {
                     dispatch_ok(data.results);
                 } else {
                     dispatch_error("No logs could be retrieved");
                 }
             }).catch((error: any) => {
                 dispatch_error(error.message);
             });
}

这个代码无法运行,因为它会重定向到登录页面。有人知道如何让它工作吗?

答案#1

使用 isomorphic-fetch 的基本认证

你拥有的代码没问题。也就是说,它会很好地发送授权头。

更多

重定向逻辑很可能出了问题。