nodejs请求静态资源404错误,后台需处理返回http请求的静态资源

nodejs小白在做的demo时后台返回主页面html后,页面请求引用的js文件,后台没有返回对应请求路径的静态资源,所以报错。原来在java开发下没有注意过这种问题,一般除了WEB-INF下的文件不能访问外,其他资源文件都可以直接用http路径访问。

1.使用http模块处理(http模块时nodejs内置模块)

public文件夹下的文件js,html默认为静态资源,后台读取这些文件然后返回给前台。
 1 var http = require('http');
 2 var fs = require('fs')
 3 const path = require('path'); 
 4 const server = http.createServer((req,res)=>{
 5     res.statusCode=200;
 6     var pathurl=path.join(__dirname, req.url);
 7     var parseurl= path.parse(pathurl);
 8     var spliturls=path.normalize( req.url).split(path.sep)
 9     var html="";
10     if(spliturls.length>0&&spliturls[1]=='public'){
11         if(parseurl.ext=='.js'){
12             res.setHeader('Content-Type','text/plain');
13             html= fs.readFileSync(path.join(__dirname, req.url));
14         }else if(parseurl.ext=='.html'){
15             res.setHeader('Content-Type','text/html');
16             html= fs.readFileSync(path.join(__dirname, req.url));
17         }
18     }else{
19         res.setHeader('Content-Type','text/html');
20         html= fs.readFileSync(path.join(__dirname, 'src/index.html'));
21     }
22   res.end(html)
23 })
24 server.listen('3000','127.0.0.1',()=>{
25     console.log(`服务器运行在 http://127.0.0.1:3000/`);
26 })

2.使用express模块(nodejs的一个web框架,封装了http模块)

 1 var express = require("express");
 2 var app = new  express();
 3 const path = require('path');
 4 app.use(express.static(path.join(__dirname,'public')))
 5 app.use('/',function(req,res){
 6     res.setHeader('Content-Type','text/html');
 7     var html= fs.readFileSync(path.join(__dirname, 'src/index.html'));
 8     res.end(html)
 9 })
10 app.listen('3000','127.0.0.1')

其中express.static是设置静态资源的目录,如果请求这个目录下的文件,则会返回对应文件。这里需要注意的是前台请求的文件路径如果是相对路径,则从public下面的文件开始,不包括public,否则取不到文件,然后又执行下面的use,返回的数据就不对了。

  测试项目的实际静态资源的路径: E:mywv estbbpublic,其中testbb是项目名称,因此如果请求E:mywv estbbpublicindex.js文件的http请求路径是http://127.0.0.1:3000/index.js,而不是http://127.0.0.1:3000/public/index.js。

原因:

express.static(path.join(__dirname,'public'))调用的是 serve-static/index.js中的 

 1 function serveStatic (root, options) {
 2   if (!root) {
 3     throw new TypeError('root path required')
 4   }
 5 
 6   if (typeof root !== 'string') {
 7     throw new TypeError('root path must be a string')
 8   }
 9 
10   ......此处省略部分代码.....
11   .......
12   // construct directory listener
13   var onDirectory = redirect
14     ? createRedirectDirectoryListener()
15     : createNotFoundDirectoryListener()
16 
17   return function serveStatic (req, res, next) {
18     if (req.method !== 'GET' && req.method !== 'HEAD') {
19       if (fallthrough) {
20         return next()
21       }
22 
23       // method not allowed
24       res.statusCode = 405
25       res.setHeader('Allow', 'GET, HEAD')
26       res.setHeader('Content-Length', '0')
27       res.end()
28       return
29     }
30 
31     var forwardError = !fallthrough
32     var originalUrl = parseUrl.original(req)
33     var path = parseUrl(req).pathname
34 
35     // make sure redirect occurs at mount
36     if (path === '/' && originalUrl.pathname.substr(-1) !== '/') {
37       path = ''
38     }
39 
40     // create send stream
41     var stream = send(req, path, opts)
42 
43    ......此处省略部分代码......
44     ...........
45 
46     // pipe
47     stream.pipe(res)
48   }
49 }
调用express.static时,使用的serveStatic (root, options)函数,参数root为E:mywv	estbbpublic,创建发送流(send(req, path, opts)),然后在发送文件时stream.pipe(res).当前端请求路径是
http://127.0.0.1:3000/public/index.js文件时,pipe输出文件使用的文件路径生成是有误的导致文件找不到。
下图是stream.pipe输出文件时,文件路径的生成。



原文地址:https://www.cnblogs.com/xiaozhuyuan/p/7207682.html