2017-06-15 58 views
2

我正在使用restify構建休息api,並且我需要允許發佈正文以獲取請求。我使用bodyparser,但它只給出一個字符串。我希望它是一個像普通的post端點一樣的對象。Restify GET請求正文

我該如何將它轉換爲對象?這裏是我的代碼:

const server = restify.createServer(); 
server.use(restify.queryParser()); 
server.use(restify.bodyParser()); 
server.get('/endpoint', function (req, res, next) { 
    console.log(typeof req.body); 
    console.log(req.body && req.body.asd); 
    res.send(200); 
}); 
+0

「我需要允許帖子主體獲取請求」 - 這是一個非常奇怪的需求。 HTTP規範警告不要使用有效載荷進行GET請求。圍繞他們設計你的系統是一個奇怪的選擇。 – Quentin

+0

您需要提供[mcve]。您似乎提供了所有必需的服務器端代碼,但不是您希望它處理的輸入。請求是什麼樣的?特別是,什麼是Content-Type頭和什麼是請求體? (你是否確認你正確地生成它們?) – Quentin

回答

1

的bodyParser中的RESTify不會默認爲有效解析JSON(我假設你正在使用),對於正在使用的GET方法請求的主體。你必須按鍵提供一個配置對象來bodyParser的初始化與requestBodyOnGet爲true:

server.use(restify.bodyParser({ 
    requestBodyOnGet: true 
})); 

爲了確保請求的主體將是JSON,我也建議你檢查內容類型在您的端點處理程序中;例如:

const server = restify.createServer(); 
server.use(restify.queryParser()); 
server.use(restify.bodyParser({ 
    requestBodyOnGet: true 
})); 
server.get('/endpoint', function (req, res, next) { 
    // Ensures that the body of the request is of content-type JSON. 
    if (!req.is('json')) { 
     return next(new restify.errors.UnsupportedMediaTypeError('content-type: application/json required')); 
    } 
    console.log(typeof req.body); 
    console.log(req.body && req.body.asd); 
    res.send(200); 
});