簡體   English   中英

setHeader(“ Content-Type”,value)是否需要node.js http“ value”?

[英]node.js http “value” required in setHeader(“Content-Type”, value)?

我得到文件extname,但未定義並拋出錯誤是:

"value" required in setHeader("Content-Type", value)

getFileType.js

const path = require('path')

const mimeType = {
    "js": "text/javascript",
    "css": "text/css",
    "png": "image/png",
    "jpg": "image/jpg",
    "gif": "image/gif",
    "html": "text/html"
}

module.exports = (filePath) => {
    let extFileName = path.extname(filePath)
        .split('.')
        .pop()
        .toLowerCase()

    if (!extFileName) {
        extFileName = filePath
    }

    return mimeType[extFileName] || mimeType['txt']
}

然后我叫mimeType

const mimeType = require('./getFileType')

if (stats.isFile()) {
    const fileType = mimeType(filePath)

    res.statusCode = 200;
    res.setHeader('Content-Type', fileType)
    fs.createReadStream(filePath).pipe(res)
}

當我刷新瀏覽器時,cmd控制台:setHeader(“ Content-Type”,value)中是否需要“ value”?

當我調試器const fileType = mimeType(filePath)得到'undefined'

和瀏覽器錯誤:E:\\ forld \\ README.md不是目錄或文件

我不明白為什么?

我假設您提供的文件的擴展名與mimeType對象中的擴展名不同。 如果是這種情況,您將返回默認值mimeType['txt']mimeType對象中沒有txt鍵。 因此,將txt鍵添加到mimeType對象。

const mimeType = {
    "js": "text/javascript",
    "css": "text/css",
    "png": "image/png",
    "jpg": "image/jpg",
    "gif": "image/gif",
    "html": "text/html",
    "txt": "application/text"
}

暫無
暫無

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

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