Nodejs request static resource 404 error, background need to handle static resources returning HTTP request

Source: Internet
Author: User

Nodejs Small white in the demo when the background back to the main page HTML, the page request reference to the JS file, the background does not return the corresponding request path static resources, so error. Originally in Java Development did not pay attention to this problem, generally in addition to web-inf under the file can not be accessed, other resources files are directly accessible with the HTTP path.

1. Processing with HTTP module (Nodejs built-in module when HTTP module)

Files under the public folder js,html default to static resources, which are then read back to the foreground.
1 varHTTP = require (' http ');2 varFS = require (' FS ')3Const PATH = require (' path '); 4Const SERVER = Http.createserver ((req,res) = ={5res.statuscode=200;6     varPathurl=Path.join (__dirname, req.url);7     varParseurl=Path.parse (pathurl);8     varspliturls=path.normalize (Req.url). Split (PATH.SEP)9     varHtml= "";Ten     if(spliturls.length>0&&spliturls[1]== ' public '){ One         if(parseurl.ext== '. js '){ ARes.setheader (' Content-type ', ' Text/plain '); -Html=Fs.readfilesync (Path.join (__dirname, Req.url)); -}Else if(parseurl.ext== '. html '){ theRes.setheader (' Content-type ', ' text/html '); -Html=Fs.readfilesync (Path.join (__dirname, Req.url)); -         } -}Else{ +Res.setheader (' Content-type ', ' text/html '); -Html= Fs.readfilesync (Path.join (__dirname, ' src/index.html '))); +     } A res.end (HTML) at }) -Server.listen (' Up ', ' 127.0.0.1 ', () ={ -Console.log (' server running on http://127.0.0.1:3000/'); -})

2. Using the Express module (NODEJS, a web framework that encapsulates the HTTP module)

1 varExpress = Require ("Express");2 varApp =NewExpress ();3Const PATH = require (' path ');4App.use (Express.static (Path.join (__dirname, ' public ')))5App.use ('/',function(req,res) {6Res.setheader (' Content-type ', ' text/html ');7     varHtml= Fs.readfilesync (Path.join (__dirname, ' src/index.html ')));8 res.end (HTML)9 })TenApp.listen (' 3000 ', ' 127.0.0.1 ')

Where express.static is the directory where static resources are set, and if a file is requested in this directory, the corresponding file is returned. It is important to note that the file path of the foreground request, if it is a relative path, starts with a file under public, does not include public, otherwise the file is not taken and then the following use is performed, and the returned data is incorrect.

The path to the actual static resource of the test project: E:\mywv\testbb\public, where TESTBB is the project name, so if the HTTP request path for the E:\mywv\testbb\public\index.js file is 127.0.0.1:3000/index.js, not http://127.0.0.1:3000/public/index.js.

Reason:

Express. Static (Path.join (__dirname,' public ')) is called in Serve-static/index.js.

1 functionservestatic (root, options) {2   if(!root) {3     Throw NewTypeError (' Root path required ')4   }5 6   if(typeofRoot!== ' string ') {7     Throw NewTypeError (' Root path must be a string ')8   }9 Ten   ...... Part of the code is omitted here ..... One   ....... A   //Construct Directory Listener -   varOndirectory =redirect -?Createredirectdirectorylistener () the : Createnotfounddirectorylistener () -  -   return functionservestatic (req, res, next) { -     if(Req.method!== ' GET ' && req.method!== ' HEAD ') { +       if(Fallthrough) { -         returnNext () +       } A  at       //Method Not allowed -Res.statuscode = 405 -Res.setheader (' Allow ', ' GET, HEAD ') -Res.setheader (' content-length ', ' 0 ') - res.end () -       return in     } -  to     varForwarderror =!Fallthrough +     varOriginalurl =parseurl.original (req) -     varPath =parseURL (req). Pathname the  *     //Make sure redirect occurs at Mount $     if(Path = = = '/' && originalUrl.pathname.substr (-1)!== '/') {Panax NotoginsengPath = ' -     } the  +     //Create send Stream A    var stream = Send (req, path, opts) the  +    ...... Part of the code is omitted here ... -     ........... $  $     //Pipe - stream.pipe (RES) -   } the}

Call Express.  Static , the servestatic (root, options) function is used, and the parameter root is E:\mywv\testbb\public, creating a Send stream (    send (req, path, opts), and then Stream.pipe (RES) when the file is sent. The current-side request path is
Http://127.0.0.1:3000/public/index.js file, the pipe output file uses a file path generation that is incorrect, causing the file to not be found.
is the Stream.pipe output file when the file path is generated.

Nodejs request static resource 404 error, Background needs to process static resources that return HTTP requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.