簡體   English   中英

我正在嘗試創建一個簡單的模塊但不起作用。 節點JS

[英]I'm trying create a simple module but doesn't work. Node JS

我是 Node JS 的新手,在這個網站和英語:)) 抱歉所有外語問題。

可能我在此代碼上收到“返回”錯誤。 當我添加 hi.myFunc(); function 我在終端出現以下錯誤:

_http_outgoing.js:679
  if (msg.finished) {
          ^

TypeError: Cannot read property 'finished' of undefined
    at write_ (_http_outgoing.js:679:11)
    at write (_http_outgoing.js:661:15)
    at Object.module.exports.myFunc (C:\Users\benom\Desktop\Her Şey\HTML\hi.js:3:9)
    at Server.<anonymous> (C:\Users\benom\Desktop\Her Şey\HTML\app.js:12:16)
    at Server.emit (events.js:315:20)
    at parserOnIncoming (_http_server.js:874:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)

我該如何解決這個問題?

我得到了這個練習的 3 個文件。

應用程序.js

const http = require("http");
const fs = require("fs");
const hi = require("./hi.js");

fs.readFile("./index.html", (err, data) => {
    if (err) {
        throw err;
    } else {
        http.createServer((req, res) => {
            res.writeHead(200, { "Content-Type": "text/html; charset=utf8" });
            res.write(data);
            hi.myFunc(req.url, res.write);
            res.end();
        }).listen(3000);
    };
});

嗨.js

module.exports.myFunc = function (url, res) {
    if (url === "/") {
        res("huh");
    };
};

索引.html

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: rgba(15, 15, 15, .96);
            color: rgb(255, 255, 255);
        }
    </style>
</head>
<body>

</body>
</html>

如果您想將res.write傳遞給其他一些 function,您可以將 object .bind()傳遞給它,如下所示:

hi.myFunc(req.url, res.write.bind(res));

沒有這個,當你將res object 傳遞給另一個 function 時,它會丟失,你最終只會引用 then .write 然后,當有人試圖調用它時,它沒有被正確的 object 調用,它會導致錯誤。

暫無
暫無

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

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