【问题标题】:react-native fetch and basic authenticationreact-native fetch 和基本身份验证
【发布时间】:2016-04-21 07:54:18
【问题描述】:

我尝试通过以下语法使用 fetch:

fetch("https://user:password@url", {
   ...
}).then((response) => {
   ...
}).done();

相同的 url 在 CURL 中有效,但在 React Native 中返回 401。

有什么想法吗?

谢谢, 保罗

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我发现https://user:password@url 这种格式在 CURL 和 node 中效果很好,但在 fetch 中效果不佳。

    我必须使用 base-64 npm 模块并通过 Headers 对象。

    // https://www.npmjs.com/package/base-64
    const base64 = require('base-64');
    
    ...
    
    var headers = new Headers();
    headers.append("Authorization", "Basic " + base64.encode("user:password"));
    
    fetch("https://url", {
        headers: headers
      })
      .then((response) => { ... })
      .done();
    `
    

    【讨论】:

    • 能否请您在这里分享npm包名称..!
    • 对我来说,这仅在调试模式下有效。大家有遇到过这样的问题吗?
    • 我正在使用 rn-fetch-blob RNFetchBlob.base64.encode(authString)
    • @MaheshK,它被称为base-64npmjs.com/package/base-64
    【解决方案2】:

    您可以使用 btoa() 而不是使用 base_64 模块。 btoa()Window 上的一个函数。

    【讨论】:

    • 这发生在 React Native 和 btoa 中,至少在那时,我认为是不可用的。
    猜你喜欢
    • 2017-07-12
    • 2016-07-01
    • 2017-10-06
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多