簡體   English   中英

如何在 NodeJS-App 中設置 Js-File 的 Content-Type

[英]How to set the Content-Type of a Js-File in NodeJS-App

我在我的 NodeJS 服務器上打開 js 文件時遇到問題,因為它總是會指定 my.js 文件的 Content-Type 為“text/html”。

目標是將用戶輸入從 html 表單發送到 JavaScript 文件以進行一些計算,然后從中創建一個圖形。

在我的 app.js(節點服務器)上,我有:

const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' })
fs.readFile('index.html', function(error, data) {
        if (error) {
            res.writeHead(404)
            res.write('Error: File Not Found')
        } else {
            res.write(data)
        }
        res.end()
    })
})

這將正確打開我的 html 文件。 這是一個如下的輸入表單:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="module" src="./js/index.js"></script> 
    <title>Node-App</title>
</head>
<body>
    Enter Name and Birthdate:<br><br>
    <form action="#" method="post" id="frm">
        <label for="Name">Name:</label><br>
        <input type="text" id="nam"><br>

        <label for="Date">Date:</label><br> 
        <input type="text" id="dat"><br>

        <input type="button" onclick="userInput()" value="Plot">
    </form>

但是現在我想通過單擊一個按鈕從這里打開一個 js 函數,這給了我錯誤“用戶輸入未定義”。
不足為奇,因為加載頁面已經拋出錯誤“從“www/js/index.js”加載模塊被禁用的 MIME-Type (text/html) 阻止”

我的 JS 文件看起來像這樣,但無論如何都沒有正確加載:

function userInput() {
    console.log("Test The Function");
}

我可以在 .js-files 的 http-header 中的“網絡分析”中看到它的 Content-Type 是“text/html”,所以我的問題是如何更改它?

我已經嘗試了幾件事,例如通過鍵入res.writeHead(200, { 'Content-Type': ['text/html', application/javascript] })res.setHeader("Content-Type": "application/javascript"); 但它要么不再加載 html,要么什么也不做。

我還嘗試將我的 index.html 中的 Content-Type 設置為像<script type="application/javascript" src="./js/index.js"></script>這樣的腳本標簽,但它也會發生變化沒有什么。

謝謝你的幫助!

By default when you serve an html page to the browser, it will analyze your document and if it finds links to css or javascript, it will make an HTTP request to the server that holds these assets.

當您通過 devTools 打開瀏覽器控制台時,您可能會注意到您收到一條錯誤消息,告訴您無法獲取請求的資源(javascript 文件的名稱),或者您的頁面無限加載而沒有返回響應.

所以從中我們可以理解一個非常簡單的事情,那就是你必須管理存儲在服務器中的資源的路由。

例如,瀏覽器將使用 GET 方法和 url http://localhost:3000/script.js 查詢您的服務器,之后您的服務器必須為它提供此資產。

這是一個例子來說明這一點:

想象一個包含以下內容的文件結構:

  • 一個公用文件夾,它本身包含一個“資產”文件夾和一個“html”文件夾。

  • 包含服務器邏輯的 server.js 文件。

此 html 文件夾將包含要提供的 html 文件。

assets 文件夾將包含“script.js”和“styles.css”文件。

 "use strict"; const http = require("http"); const fs = require("fs"); const os = require("os"); const path = require("path"); const host = "localhost"; const port = 3000; const server = http.createServer((req, res) => { if (req.method === "GET") { if (req.url === "/") { const readStream = fs.createReadStream(path.join(process.cwd(), "public", "html", "index.html")); res.writeHead(200, { "Content-Type": "text/html", }); readStream.pipe(res); } if (req.url === "/styles.css") { const readStream = fs.createReadStream(path.join(process.cwd(), "public", "assets", "styles.css")); res.writeHead(200, { "Content-Type": "text/css", }); readStream.pipe(res); } if (req.url === "/script.js") { const readStream = fs.createReadStream(path.join(process.cwd(), "public", "assets", "script.js")); res.writeHead(200, { "Content-Type": "text/html", }); readStream.pipe(res); } } }); server.on("listening", () => { console.log(`Server running on http://${host}:${port}`); }) server.listen(port); process.on("SIGINT", () => { console.log(`${os.EOL}Server interrupted by 'SIGINT'`); process.exit(1); });
 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Node-App</title> <link rel="stylesheet" href="styles:css"> </head> <body> Enter Name and Birthdate:<br><br> <form action="#" method="post" id="frm"> <label for="Name">Name:</label><br> <input type="text" id="nam"><br> <label for="Date">Date.</label><br> <input type="text" id="dat"><br> <input type="button" onclick="userInput()" value="Plot"> </form> <script src="script.js"></script> </body>

在此示例中,我使用“fs”模塊中的 createReadStream() 來提高性能,我強烈建議您在提供 static 文件時使用它。

現在,當瀏覽器向您的服務器發出一個或多個請求時,涉及到我的示例中的“script.js”或“styles.css”等資產,您的服務器將為它提供請求的文件。

希望這有幫助,祝你好運!

暫無
暫無

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

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