簡體   English   中英

RectJS 和 NodeJS:從客戶端對 url 進行編碼和解碼以提供服務

[英]RectJS & NodeJS : Encode & decode url from client to serve

 const quParams = {sample1: 'one', sample2: 'one+one/two', sample3: 'testing'} if (Object.keys(quParams).length) { const api_params = `&${Object.keys(quParams).map(x => `${x}=${quParams[x]}`).join("&")}` console.log('api_params>>>>>>>>>>', api_params) }

`

 const quParam = {sample1: 'one', sample2: 'one%2Bone%2Ftwo'} let objKeys = Object.keys(quParam); let quParamValue = '' for (item of objKeys) { quParam[item]; if (item === 'sample2') { quParamValue = quParam[item].replaceAll('%2F', '/').replaceAll('%2B','+') console.log('quParamValue>>>>>>', quParamValue) } }

`客戶端url的查詢參數之一在參數中有特殊字符(sample2)

https://example.com/endpointService?sample1=one&sample2=one+one/two

當將此 url 從客戶端傳遞到服務器端時,它被編碼為

https://testing.com/endpointService?sample1=one&sample2=one%2Bone%2Ftwo

將此編碼 URL 傳遞給 RESTFUL api 服務時,沒有給出良好的響應。

如何處理這種情況..

我們必須在哪里以及如何使用 JS 對查詢值進行編碼和解碼

客戶端 (React JS) >>> 服務器 (Express JS) >>> Restful 服務

如何在不替換節點js的情況下做到這一點

大多數庫會為您處理此問題,因此當您發送/獲取請求 object 時,參數已經分別編碼/解碼。 如果您必須自己執行此操作,您可以使用decodeURI function:

const uri = 'https://mozilla.org/?x=1+ a/ 2';
const encoded = encodeURI(uri);
console.log(encoded);
// expected output: "https://mozilla.org/?x=1+%20a/%202"

try {
  console.log(decodeURI(encoded));
  // expected output: "https://mozilla.org/?x=1+ a/ 2"
} catch (e) { // catches a malformed URI
  console.error(e);
}

簽出: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

在 express 中,您可以檢索 url 並在路由處理程序中查詢參數:

app.get('/api/users/:name', function(req, res) {
  const queryParam = req.query.name // for example
  res.send('Hello ' + req.name + '!');
});

如果您不滿意並且需要以特殊模式獲取參數,您可以創建自定義中間件並按照您希望的方式解析查詢字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM