如何正确在Fetch URL中使用authorization_token发起POST请求
你的问题确实出在Fetch URL中没有正确引用res.authorization_token变量,导致请求URL无效,进而触发NetworkError。以下是具体修正方案:
核心错误点
你当前的Fetch URL用双引号包裹,其中res.authorization_token只是作为静态文本存在,并没有被解析为变量值:
fetch("https://api.example//payments/v1/authorizations/res.authorization_token/order", requestOptions)
另外URL中存在多余的斜杠(example//payments),这也会导致请求路径无效。
修正后的完整代码
使用JavaScript的模板字面量插入变量值,同时修正URL的斜杠问题:
function(res) { console.log("Response from the authorize call:") console.log(res) var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Authorization", "Basic mypw-usn"); var raw = JSON.stringify({ "intent": "buy", "purchase_country": "GB", "purchase_currency": "GBP", "locale": "en-GB", "order_amount": 10, "order_tax_amount": 0, "order_lines": [{ "type": "physical", "reference": "19-402", "name": "Battery Power Pack", "quantity": 1, "unit_price": 10, "tax_rate": 0, "total_amount": 10, "total_tax_amount": 0 }], "merchant_urls": { "confirmation": "http://localhost:8888/jcart/mypage1.php", "authorization": "http://localhost:8888/jcart/mypag1e.php" } }); var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow' }; // 修正后的Fetch调用 fetch(`https://api.example/payments/v1/authorizations/${res.authorization_token}/order`, requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); }
关键修正说明
- 模板字面量插入变量:用反引号(
`)包裹URL字符串,通过${res.authorization_token}将动态变量值插入到URL中,确保请求URL包含有效的授权令牌。 - 修正URL格式:将
https://api.example//payments改为https://api.example/payments,移除多余的斜杠,保证路径合法。
修改后,Fetch请求会使用正确的令牌构造URL,可解决你遇到的NetworkError问题。
内容的提问来源于stack exchange,提问作者Ria
相关产品推荐
相关产品推荐

