簡體   English   中英

有沒有辦法判斷 POST(正文)請求的格式是 URL 編碼的查詢字符串還是 JSON 數據?

[英]Is there a way to tell if a POST (body) request is formatted as a URL encoded query string or JSON data?

我正在編寫服務器端代碼來處理傳入的發布請求(使用 NodeJS 和 Express)。

如果進入服務器的請求被格式化為 JSON 數據,那么我想使用 JSON.parse,但是如果傳入的數據被格式化為 URL 編碼的查詢字符串,那么在該數據上使用 JSON.parse 會給我以下錯誤. 有什么建議? 代碼在底部。

在此處輸入圖片說明

app.post("/", (req, res) => {
    
    let parsedData;
   
    // if request.body is received as JSON data, I want to put it inside the loop below and parse it and then set parsedData equal to that parsed data.
    // if the request.body is received as url encoded data, I just want to set parsedData = req.body
    for (var key in req.body) {
            parsedData = JSON.parse(key);
        }
        
    
})

其實我是看出來了! 基本上我創建了一個單獨的函數來查看我是否可以 JSON PARSE req.body

function isJSONObject(value) {
    try {
        JSON.parse(value)
    } catch {
        return false;
    }
    return true;
}

暫無
暫無

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

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