【发布时间】:2015-11-25 05:58:41
【问题描述】:
我正在尝试使用 express 和 body-parser 库来创建一个简单的节点服务器。正如我在下面的示例中所述,它不支持静态文件。我犯了什么错误?请帮助我。
server.js
var express = require("express");
var bodyParser =require("body-parser");
var app = express();
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function(req,res)
{
res.sendfile("index.html");
});
app.listen(3000,function()
{
console.log("Server started on Port 3000");
});
Package.json
{
"name": "blog post",
"version": "0.0.1",
"description": "Package.josn for node server",
"repository": {
"type": "git",
"url": ""
},
"private": true,
"dependencies": {
"body-parser": "^1.14.1",
"express": "^4.13.3"
}
}
我已按照建议更新了我的 server.js。
server.js(更新)
var express = require("express");
var bodyParser =require("body-parser");
var app = express();
//Here we are configuring express to use body-parser as middle-ware.
//app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res)
{
res.sendfile("index.html");
});
app.listen(3000,function()
{
console.log("Server started on Port 3000");
});
工作版本 server.js
var express = require("express");
var bodyParser =require("body-parser");
var app = express();
//Here we are configuring express to use body-parser as middle-ware.
//app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(__dirname + '/'));
app.get('/',function(req,res)
{
res.sendfile("index.html");
});
app.listen(3000,function()
{
console.log("Server started on Port 3000");
});
【问题讨论】:
-
请不要将您最初在问题中的代码更改为现在包含人们推荐的内容。这会掩盖您提出的原始问题,并使根据原始问题提供的答案无效。如果您已经采纳了一些建议,但现在仍然卡住,您可以为您的问题添加新信息。
-
@jfriend00 我已经按照你的建议更新了我的问题。请帮助我克服这个问题。作为资深会员,如果能推荐 StackOverflow 允许在 cmets 区域进行编码格式化,那就太好了。在 cmets 区添加代码非常困难。
-
非常感谢@jfriend00。在我删除公众后它工作正常。
标签: javascript node.js express frontend mean-stack