[英]Cannot get included js file in the Node.js app
I have a simples pure Node.js app. 我有一个简单的纯Node.js应用程序。 Its structure looks like this:
其结构如下所示:
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')}`))
After launching it can find common.js
启动后可以找到
common.js
but returns the contents of views/index.html
instead of the script itself: 但返回
views/index.html
的内容,而不是脚本本身:
common.js
: common.js
:
console.log('Common js here to help!')
Also it outputs errors: 它还输出错误:
So, supposedly this is something simple, but I cannot figure out what exactly.
因此,据说这很简单,但是我无法弄清楚到底是什么。
You are serving the same file on every request. 您在每个请求上都提供相同的文件。 These lines will always respond with the contents of the file "node.html".
这些行将始终以文件“ node.html”的内容进行响应。
const filePath = 'views/node.html'
fs.readFile(filePath, (err, content) => {
res.end(content)
});
According to node-static documentation a correct way to serve a directory would be: 根据节点静态文档 ,提供目录的正确方法是:
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.