简体   繁体   English

如何使用 express js 和函数 http 创建服务器 nodejs

[英]how use express js and function http create server nodejs

I have de following code in node js:我在节点 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...);
 });

i need insert expressjs in my application for work with express js for example :我需要在我的应用程序中插入 expressjs 以使用 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);

how join the two code in one如何将两个代码合二为一

By joining 2 code in one , i guess you want to use the middleware you described in 1st file通过将 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);

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

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