如何处理 fetch api 中的“+”号?

问题描述 投票:0回答:1

这是我的代码:

function GETdynamoDBapi(phoneNumber) {
    return new Promise(function (resolve, reject) {
        fetch(
            'https://api?phoneNumber=' +
                phoneNumber
        )
            .then((res) => {
                return res.json();
            })
            .then((res) => {
                resolve(data);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

我尝试过以下两种有和没有

+
的情况。我的数据库表上有“4100000000”和“+4100000000”数据。电话号码在数据库中定义为字符串。

let response = await GETdynamoDBapi('+4100000000'); //error return data
let response = await GETdynamoDBapi('4100000000'); //return date success

如何处理“+”号?谢谢!

(已编辑)
我还尝试在 Insomnia 上测试 API https://api?phoneNumber=+4100000000 ,效果很好。但是当我尝试遵循我的代码时,它无法返回任何数据。

        fetch(
            'https://api?phoneNumber=+4100000000'
        )
javascript react-native get fetch-api
1个回答
0
投票

您忘记了编码值:

fetch(`https://api?phoneNumber=${encodeURIComponent(phoneNumber)}`)

这样,它就会变成例如

phoneNumber=%2B1234567890
,以便在服务器上解码时它会变回
+1234567890
。否则,
+
可能在服务器上被解释为空格字符

您应该始终对查询参数进行编码,否则至少会出现错误,最坏的情况会出现安全漏洞。

另一种更具表现力的方式是使用

URLSearchParams
:

fetch(`https://api?${new URLSearchParams({ phoneNumber })}`)

或者一个

URL
物体:

const url = new URL('https://api')
url.searchParams.set('phoneNumber', phoneNumber)
fetch(url)

或者,您可以使用标记模板函数,例如

uri-tag
:

import uri from 'uri-tag'

fetch(uri`https://api?phoneNumber=${phoneNumber}`)

另一个注意事项:您正在使用显式承诺构造反模式。不需要任何

new Promise
,因为
fetch
已经返回了一个承诺,否则你无法做到
.then

function GETdynamoDBapi (phoneNumber) {
  return fetch(`https://api?${new URLSearchParams({ phoneNumber })}`)
    .then(res => res.json())
}

或者您可以创建函数

async
并使用
await
,那么在添加更多逻辑的情况下维护起来会更容易,并且与您显然已经使用的其他函数保持一致
async
/
await 

async function GETdynamoDBapi (phoneNumber) {
  const response = await fetch(`https://api?${new URLSearchParams({ phoneNumber })}`)
  return await response.json()
}

抢先评论:阅读此处了解我为什么使用

return await

© www.soinside.com 2019 - 2024. All rights reserved.