[英]How to set Content-Type header in node.js
我在node.js中執行以下代碼。 代碼運行正常,但教程告訴我們:
現在返回並添加帶有application / json值的Content-Type標頭並再次運行請求。 您將從服務器返回“您發送的JSON”消息。
1)我無法理解如何為此程序設置標題!
2)此外如果我在沒有設置標題的情況下運行程序,則應顯示消息“Server requires application / json”。 我沒有看到它在任何地方顯示。 應該在哪里顯示?
const express = require('express');
const app = express();
const requireJsonContent = () => {
return (req, res, next) => {
if (req.headers['content-type'] !== 'application/json') {
res.status(400).send('Server requires application/json')
} else {
next()
}
}
}
app.get('/', (req, res, next) => {
res.send('Welcome Home');
});
app.post('/', requireJsonContent(), (req, res, next) => {
res.send('You sent JSON');
})
app.listen(3000);
我在你的代碼中看到的是,你定義的函數requireJsonContent沒有參數。 因此,您應該將(req,res,next)添加為函數的參數。 此外,在它內部,你返回一個沒有執行的功能。 但是,我認為您不需要該功能,您的代碼應該是這樣的:
app.post('/', (req, res) => {
if (req.headers['content-type'] !== 'application/json') {
res.status(400).send('Server requires application/json')
} else {
res.send('You sent JSON');
}
})
使用express 4.x,您可以使用res.set()
或res.append()
。 在這里閱讀兩種方法之間的差異
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.