简体   繁体   English

Express.js 中的静态路由返回 404 错误

[英]Static Routing in Express.js returning 404 Error

I'm trying to create routing for different pages of my website, using express.js.我正在尝试使用 express.js 为我网站的不同页面创建路由。 When going to 127.0.0.1:8080, it loads the index.html page fine, however, when I go to 127.0.0.1:8080/questionaire, it comes back with a 404 error and doesn't load questionaire.html.当转到 127.0.0.1:8080 时,它可以正常加载 index.html 页面,但是,当我转到 127.0.0.1:8080/questionaire 时,它​​返回 404 错误并且不加载 questionaire.html。 I thought that using the line:我认为使用该行:

app.use(express.static('client', { extensions: ['html'] }));

meant that this would be possible, however, it doesn't work.意味着这是可能的,但是,它不起作用。 If there is a better way to do this then fixing the solution, inform me please.如果有更好的方法可以解决此问题,请告知我。

Directory目录

client
-- index.html
-- index.js
-- questionaire.html
-- questionaire.js
svr.js
viewapi.js

svr.js svr.js

'use strict';

const express = require('express');
const app = express();

const view_api = require('./viewapi');

app.use(express.static('client', { extensions: ['html'] }));

const api = require('./api');

app.use('/view', view_api); // routing to api which will get data in form of JSON

app.listen(8080);

I just tried your setup and loading questionare.html worked fine for me.我刚刚尝试了您的设置并加载 questionare.html 对我来说效果很好。 Did you receive any other errors from the Express server when you tried to load the page?当您尝试加载页面时,您是否收到来自 Express 服务器的任何其他错误? I'm asking because I'm not sure what the contents are inside viewapi.js so when I tested it, I didn't have that file.我问是因为我不确定viewapi.js的内容,所以当我测试它时,我没有那个文件。

However, to answer this:但是,要回答这个问题:

If there is a better way to do this then fixing the solution, inform me please.如果有更好的方法可以解决此问题,请告知我。

it's good practice to separate the assets that you serve (html, css, js, images, etc.).将您提供的资源(html、css、js、图像等)分开是一种很好的做法。 For example, you could create sub-folders inside your client folder and put your static files in the appropriate folder.例如,您可以在client文件夹中创建子文件夹并将静态文件放在适当的文件夹中。

You can also find examples and better documentation here: https://expressjs.com/en/starter/static-files.html您还可以在此处找到示例和更好的文档: https : //expressjs.com/en/starter/static-files.html

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

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