node 服务器

node 正常的创建服务器代码, require("http")  http.createServer(function(req, res){
    res.write('<head><meta charset="utf-8"></head>');
    res.write("旺旺的nodejs 服务器搭建成功了");
    res.end();
    console.log("----链接了!!!!---");
}).listen(3000);

express 框架创建服务器

const express = require('express');

const PORT = process.env.PORT || 3000;
const app = express();

// use 方法 app.use([path,] function [, function…]) 
app.use((req, rss, next)=>{
	console.log("%O", req); // 默认路径
    console.log('Time: %d', Date.now()); // 时间打印
    /*// 假如path = '/admin'   GET 'http://www.example.com/admin/new'
        console.log(req.originalUrl); // '/admin/new'
        console.log(req.baseUrl); // '/admin'
        console.log(req.path); // '/new'
    */
	next();
});

// get
// 
app.get('/', (req, res) => {
	res.send("Hello world");
    console.log(req.query);// ''
});

// get请求
// http://localhost:3000/student?name=%22Hanxiaohong%22&age=29
app.get('/student', (req, res) => {
	res.send("Hello world");
    console.log(req.query);//{ name: '"Hanxiaohong"', age: '29' }
});

// post请求   POST请求在express中不能直接获得,必须使用body-parser模块
// 使用后,将可以用req.body得到参数。但是如果表单中含有文件上传,那么还是需要使用formidable模块
// post请求要借助body-parser模块。使用后,将可以用req.body得到参数,使用模板引擎,表单提交。
// 
var bodyParser = require('body-parser');
app.post("/", function(req, res) {
    console.log(req.body);
});

app.listen(PORT, () => {
	console.log("Server running on port %d", PORT);
});

npm init 初始化项目

猜你喜欢

转载自blog.csdn.net/W_han__/article/details/102640965
今日推荐