簡體   English   中英

無法在Node.js應用中獲取包含的js文件

[英]Cannot get included js file in the Node.js app

我有一個簡單的純Node.js應用程序。 其結構如下所示:

在此處輸入圖片說明

The problem is I cannot get common.js properly.
The app.mjs consists of:
import http from 'http'
import fs from 'fs'
import nStatic from 'node-static'
import chalk from 'chalk'
import debug from 'debug'

const output = debug('app')

const fileServer = new nStatic.Server('./public')

const server = http.createServer((req, res) => {
  fileServer.serve(req, res)
  const Url = new URL(req.url, 'http://localhost:3000/')
  const fileExt = Url.pathname.split('/').pop().split('.').pop()
  let aType = ''

  switch (fileExt) {
    case 'ico':
      aType = 'image/vnd.microsoft.icon'
      break
    case 'js':
      aType = 'application/javascript'
      break
    case 'json':
      aType = 'application/json'
      break
    default:
      aType = 'text/html'
      break
  }
  res.writeHead(200, { 'Content-type': aType })

  const filePath = 'views/node.html'
  // using readFile
  fs.readFile(filePath, (err, content) => {
    if (err) {
      console.log('Error has occured: ', err)
      res.end(content)
    } else {
      res.end(content)
    }
  })
})

server.listen(3000, () => output(`Listen to me ${chalk.green('3000')}`))

啟動后可以找到common.js

在此處輸入圖片說明

但返回views/index.html的內容,而不是腳本本身:

在此處輸入圖片說明

common.js

console.log('Common js here to help!')

它還輸出錯誤: 在此處輸入圖片說明 因此,據說這很簡單,但是我無法弄清楚到底是什么。

您在每個請求上都提供相同的文件。 這些行將始終以文件“ node.html”的內容進行響應。

const filePath = 'views/node.html'
fs.readFile(filePath, (err, content) => {
      res.end(content)
});

根據節點靜態文檔 ,提供目錄的正確方法是:

const http = require('http');
const NodeStatic = require('node-static');

const fileServer = new NodeStatic.Server('./public');

const server = http.createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
});
server.listen(8080);

暫無
暫無

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

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