繁体   English   中英

使用Node.js提供JavaScript文件

[英]Serving Up a Javascript file using Node.js

我正在尝试使用一个非常基础的node.js服务器提供一些静态文件。 目的是为HTML文件提供带有引用JavaScript文件的脚本标签。 在浏览器中打开应用程序时,html呈现良好,问题出在js文件上。 在浏览器中,js文件中包含html代码,而不包含js代码。

服务器代码:

var http = require('http')
var fs = require('fs')

var port = 3000;

var app = http.createServer(function(req, res){
    var html = fs.createReadStream('./index.html')

    html.pipe(res);
})

app.listen(port, function(){
    console.log('Listening on port ' + port)
})

HTML CODE(index.html):

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Hello</title>
 </head>
 <body>
  <h1>Hello</h1>
  <script src="./some.js"></script>
 </body>
</html>

JAVASCRIPT CODE(some.js):

console.log("Hello")

目录结构:

|-index.html
|-some.js
|-app.js(server)

我建议您以以下方式为需要服务的文件创建目录

|-public
    |-index.html
    |-some.js
|-app.js(server)

然后,您使用express.static来服务您创建的目录。

var express = require('express');
var app = express();
var path = require('path');
var port = 3000;

app.use(express.static(path.join(__dirname, 'public')));

app.listen(port, function(){
   console.log('Listening on port ' + port)
})

那你就跑

node app.js

不使用快递,您可以执行以下操作

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {

    var filePath = '.' + request.url;
    if (filePath == './')
       filePath = './index.html';

    var extName = path.extname(filePath);
    var contentType = 'text/html';
    switch (extName) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

    if (exists) {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                response.writeHead(500);
                response.end();
            }
            else {
                response.writeHead(200, { 'Content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    }
    else {
        response.writeHead(404);
        response.end();
    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM