【问题标题】:Why i got the output as "\"userName\"" and not like that "userName"?为什么我得到的输出是“\”userName\“”而不是那个“userName”?
【发布时间】:2020-07-02 13:06:31
【问题描述】:

为什么我得到输出 "\"userName\"" 而不是 "userName" ? 在我的示例中,我尝试做一个 get api,它附加一些数据并且该数据来自异步存储。 当我控制输出时,它会显示这样的数据:

"\"userName\""

但它应该输出 "userName" 。 解决这个问题的方法是什么?

所以我的方式有什么问题?

const getSaveUserTokenData = async (data) => {
    const url =
      'https://URL/userName,userToken,PlatformType,DeviceID?' +
      'userName=' +
      data.userName +
      '&userToken=' +
      data.googlToken +
      '&PlatformType=' +
      data.platformId +
      '&DeviceID=' +
      data.deviceId;
    await fetch(
      url,

      {
        method: 'GET',
        headers: {
          Authorization: data.azureToken,
        },
      }
    )
      .then((response) => response.json())
      .then((data) => {
        console.log('Success:', data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

【问题讨论】:

  • 有什么问题?从理论上讲,这应该有效。假设您生成的 URL 是正确的。

标签: javascript reactjs react-native rest expo


【解决方案1】:

你也可以这样写:

fetchFunction = async () => {

    let data = {
        userName: 'jon',
        userToken: 'bee22',
        PlatformType: 'os-ios',
        DeviceID: '222222'
    }


    const url = `https://yoururl.com/?userName=${encodeURIComponent(data.userName)}&userToken=${encodeURIComponent(data.userToken)}&PlatformType=${encodeURIComponent(data.PlatformType)}&DeviceID=${encodeURIComponent(data.DeviceID)}`;


    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Authorization': 'Basic ' + btoa('username:password'),
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
    });

    const json = await response.json();

    console.log(json);

}

【讨论】:

  • 你能告诉我如何用我的代码做你的例子吗?
  • 您想将这些数据传递到您的服务器吗?
  • @shira,更新了我的答案。请看看这个。
  • 我还需要添加标题..你能在上面看到我的更新吗?请尝试将我的示例修正为正确的原因。
  • @shira,您可以像这样传递我已添加到答案中的标题。
【解决方案2】:

如果你的变量名是你想要在你的 url 中的那个,试试这个:

const getData = async () => {
    let userName = 'jon';
    let userToken = 'bee22';
    let PlatformType = 'os-ios';
    let DeviceID = '222222';

    const queryString = Object.entries({
      userName,
      userToken,
      PlatformType,
      DeviceID,
    })
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&');

    
    const response = await fetch(
      'https://url...?' + queryString
    );
  };
};

注意:用户令牌不应在 url 中,而通常在请求的标头中,如下所示:

fetch(someUrl, {
  headers: {
    Authorization: userToken
  }
});

【讨论】:

  • 你知道如何使用 SQLite 吗?
  • @shira 请停止发送与此特定问题无关的通知。使用 SQLite 标签提出一个新问题,您将找到可能能够帮助您的相关贡献者
【解决方案3】:
fetch(`https://yoururl.com/${userName}`,
        { method: 'GET',
          headers: myHeaders,
          mode: 'cors',
          cache: 'default' 
})
.then(function(response) {
  //your code here
});

【讨论】:

  • 你能告诉我如何用我的代码做你的例子吗?
  • 欢迎来到stackoverflow。你能提供更多解释吗?您正在回答一个困难的问题,因为它很难测试。为什么你认为 OP 代码不起作用,为什么你的代码会起作用?
【解决方案4】:

一个更通用的解决方案是这样的:

async function get(route, ...params) {
  const url = `${route}${params.map(p => `/${p}`)}`;
  const response = await fetch(url, { method: "GET", headers });
  if (!response.ok)
    throw new Error(`Http error status: ${response.status}`);

  return response.json();
}

通过使用...params,您可以传递通用数量的参数,然后将这些参数与:

 const url = `${route}${params.map(p => `/${p}`)}`;

在你的情况下,你会这样调用方法:

const result = await get("https://url..", "jon", "bee22", "os-ios", "222222");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2016-04-06
    • 2013-09-22
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多