简体   繁体   English

Node.js 如果仅在 Assets 文件夹中找不到文件,则快速返回 404

[英]Node.js Express return 404 if file not found in only Assets folder

I am trying to create an SPA using Express with following code我正在尝试使用带有以下代码的Express创建 SPA

var express = require('express');
const path = require('path');

var app = express();

app.use('/assets', express.static(path.resolve(__dirname, 'www', 'assets')));

app.get('/*', (req, res)=>{
     res.sendFile(path.resolve('www', 'index.html'));
});

var server = app.listen(3000, function(){});

This code works good but the problem is this responds with my index.html even when a file is not found in my assets folder.此代码运行良好,但问题是即使在我的资产文件夹中找不到文件,它也会以我的index.html响应。 I want it to respond with error of 404 Not Found if some url is not present in assets folder如果资产文件夹中不存在某些 url,我希望它响应404 Not Found错误

I tried using this code after line app.use('/assets'...我尝试在app.use('/assets'...

app.use(function (req, res, next) {
    res.status(404).send("404 Not Found");
});

but not working但不工作

Issue is with问题在于

app.get('/*', (req, res)=>{
     res.sendFile(path.resolve('www', 'index.html'));
});

Instead, use相反,使用

app.get('/', (req, res)=>{
         res.sendFile(path.resolve('www', 'index.html'));
    });

So, I finally got the way to solve it所以,我终于找到了解决它的方法

app.get('/*', (req, res)=>{
    if(req.path.includes('/assets'))
    {
        fs.access(req.path, (err) => {
            if(err) 
            {
                res.status(404).send("Sorry can't find that!");
                return;
            }
        });
    }
    res.sendFile(path.resolve('www', 'index.html'));
});

In the code, I have told to check if the request is about a file located in assets folder then check if the file exists, if does not exists then send 404 error with message and just return, otherwise do nothing but return the file.在代码中,我告诉检查请求是否与位于assets文件夹中的文件有关,然后检查文件是否存在,如果不存在则发送 404 错误消息并返回,否则只返回文件。

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

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