如何使用Express.js和http.Node.js中的createServer函数



我有以下Node.js代码:

var app, fs, express
fs = require("fs")
app = require("http").createServer(function (req, res) {
  var file
  file = req.url === "/" ? "/index.html" : req.url
  console.log(req.method + " " + file)
  return fs.readFile("./views" + file, function (err, data) {
    if (err != null) {
      res.write(404)
      return res.end("<h1>HTTP 404 - Not Found</h1>")
    }
    res.writeHead(200)
    return res.end(data)
  })
})
app.listen(3000, function () {
  return console.log("running...")
})
     

我需要在我的应用程序中包含Express.js,例如:

app = express()
express = require("express")
app.use(express.bodyParser())
app.use(app.router)
app.get("/form", function (req, res) {
  res.sendfile("./form.html")
})
http.createServer(app).listen(3000)

如何组合这两个片段?

通过将2个代码合并为一个,我猜您想使用您在第一个文件

中描述的中间件
 var app = express();
 var express = require("express");
 app.use(express.bodyParser());
 app.use(app.router);
 app.get("/form", function (req,res){
  res.sendfile("./form.html");
 });
app.use(function(req, res) {
 var file;
 file = req.url === '/' ? '/index.html' : req.url;
 console.log(req.method + " " + file);
 return fs.readFile("./views" + file, function(err, data) {
 if (err != null) {
    res.write(404);
   return res.end("<h1>HTTP 404 - Not Found</h1>");
 }
res.writeHead(200);
return res.end(data);
})
http.createServer(app).listen(3000);
// Create app with Express
let app = express();
// Create a Node server for Express app
let server = http.createServer(app);
// Parse application/json
app.use(bodyParser.json());
// Parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/form", function (req,res){
  res.sendfile("./form.html");
});
app.use(function(req, res) {
  var file;
  file = req.url === '/' ? '/index.html' : req.url;
  console.log(req.method + " " + file);
  return fs.readFile("./views" + file, function(err, data) {
  if (err != null) {
         res.send(404);
  }
  res.json(data);
})

server.listen(3000);

相关内容

  • 没有找到相关文章

最新更新