app.get('/',function(req,res,next){
app.use(express.static(html file);
next();
});
app.get('/:someText',function(req,res){
var x = req.params.someText;
res.send(x);
});
我得到两个输出,但没有得到该文件的CSS的CSS。如何在node.js中获取/和/:someText?
app.get('/',function(req,res,next){
app.use(express.static(html file);
next();
});
app.get('/:someText',function(req,res){
var x = req.params.someText;
res.send(x);
});
我得到两个输出,但没有得到该文件的CSS的CSS。如何在node.js中获取/和/:someText?
正如我从代码中可以看出你缺少发送的get /。
app.get('/',function(req,res,next){
//something
//in here add res.send() and all OK.
});
请检查以了解接下来的内容。
你使用express.static
的方式是不正确的。你不应该把它传递给一个文件来返回,那就是sendFile
。 express.static
用于提供整个目录,应在get
处理程序外调用。
例如,这将在您的URL的根目录中提供一个名为public
的目录。未找到文件的任何请求将通过中间件/路由器链传递到下一个处理:
app.use(express.static(path.join(__dirname, 'public')));
重要的本应出现在您的通话app.get
,app.post
等之前,而不是一个处理器中。
所以,如果你有一个在public/myfile.html
的文件,将在http://localhost:3000/myfile.html
服务,我假设你的服务器在localhost:3000
。如果您想为网址添加一部分路径,例如http://localhost:3000/stat/myfile.html
这将是:
app.use('/stat', express.static(path.join(__dirname, 'public')));
如果你想成为一个单一的文件,那么你可以使用sendFile
,有点像这样:
app.get('/myfile.html', function(req, res) {
res.sendFile(path.join(__dirname, '/myfile.html'));
});
注意,这是挑出一个特定的文件,因此任何像CSS这样的资源需要分开处理。如果HTML,CSS等都在同一个文件夹中,那么使用express.static
来代替整个目录是有意义的。
还值得注意的是,express.static
有一个名为index
的设置,默认情况下提供一个名为index.html
的文件,如果请求进入'/'。
进一步阅读: