一入前端深似海,只敢闷头苦学识javascript
新建nodeexpress文件夹 注意 这里起名字是不容许起 express的 ,中间件 暂时忽略css
npm init -y
npm install express --save
//linux mac
sudo npm install express --save
复制代码
安装 supervisor 用于热启动html
//安装到 全局
sudo npm install supervisor -g
复制代码
var express = require('express');
var app = express();
app.get('/',function(req,res){
res.send("Hello world")
})
app.listen(8081,function(){
console.log("接口已启动")
})
复制代码
request是客户端向服务端请求的信息,response是服务器向客户端返回的信息前端
request常见方法java
reponse常见方法node
app.get('/index/:id',function(req,res){
res.json({
id:'Hello 【' + req.params.id +'】'
})
})
复制代码
总结:linux
- 安装并引用express 启用一个express 实例
- app listen 一个端口 启动一个后台服务 -app.get 设置基础的路由 吐出数据
app.get('/index.html',function(req,res){
res.send('Hello 【'+ req.query.username +'】')
})
复制代码
app.get('index/:id',function(req,res){
res.send('Hello 【'+ req.params.id +'】')
})
复制代码
app.use(express.static('public'));
app.get('/index.html',function(req,res){
res.sendFile(__dirname + "/views/" + "index.html");
})
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
Hello Node
<script type="text/javascript" src="scripts/index.js"></script>
</body>
</html>
复制代码
npm install body-parser --save
var express = require('express');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({
extended:false
})
var app = express();
app.get('/index',function(req,res){
res.sendFile(__dirname + '/views/index.html')
})
app.post('/index',urlencodedParser,function(req,res){
console.log(req.body);
res.redirect("http://www.baidu.com")//执行跳转页面
})
app.listen(8081,function(){
console.log("接口已启动")
})
复制代码
var express = require("express")
var app = express()
app.use(function(req,res,next){
console.log("必经路由");
next();
})
app.get('/index',function(req,res,next){
req.data = 123;
next();
},function(req,res,next){
console.log(req.data) //这里是能够拿到上面的赋值的
res.send("end")
})
app.listen(8081,function(){
console.log("接口已启动")
})
复制代码
应用级中间件绑定到app 对象使用app.use()和app.METHOD(),其中,METHOD是须要处理的HTTP请求的方法,例如GET、PUT、POST等等,所有小写。正则表达式
var app = express();
//没有挂载路径的中间件,应用的每一个请求都会执行该中间件
app.use(function(req,res,next){
console.log("Time:",Date.now());
next();
})
//挂载至 /user/:id 的中间件,任何指向 /user/:id 的请求都会执行它
app.use('/user/:id',function(req,res,next){
console.log("Request Type:",req.method);
next();
})
//路由和句柄函数(中间件系统),处理指向/user/:id 的GET请求
app.get('/user/:id',function(req,res,next){
res.send("USER");
})
复制代码
在一个挂载点装载一组中间件express
app.use('/user/:id',function(req,res,next){
console.log("Request URL:",req.originalUrl);
next();
},function(req,res,next){
console.log('Request Type:',req.method);
next();
})
复制代码
路由级中间件和应用级中间件同样,只是它绑定的对象为 express.Router()。与app 用法同样 router 没有特别复杂的app里的api router->只有路由相关的api mini-appnpm
var app = express();
var router = express.Router();
router.use('/user/:id',function(req,res,next){
console.log("Request URL:",req.originalUrl);
next();
},function(req,res,next){
console.log('Request Type:',req.method);
next();
})
复制代码
错误处理的中间件和其余中间件相似,只是要使用4个参数,而不是三个 参数为(err, req, res, next)。
app.use(function(err, req, res, next){
console.log(err.stack);
res.status(500).send("Something broke!")
})
复制代码
express.static(root,[options]) 惟一内置的中间件。它基于 serve-static ,负责在Express应用种提托管静态资源。 参数 root 是指体哦那个静态资源的根目录。 options参数
npm install cookie-parser
var express = require("express");
var app = express();
var cookieParser = require('cookie-parser');
//加载用于解析 cookie 的中间件
app.use(cookieParser());
复制代码
var express = require("express");
var app = express();
app.get('/',function(req,res){
res.send("hello world");
})
复制代码
路由方法源于HTTP请求方法,和express 实例相关联。
// get method
app.get('/',function(req,res){
res.send('GET request to the homepage');
})
app.post('/',function(req,res){
res.send('POST requeset to the homepage');
})
复制代码
app.get('/index/add', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res,next) {
res.send('Hello from B!')
next()
},function(req,res,next){
console.log("虽然不能够继续向客户端吐数据,可是nodejs代码仍是能够执行的")
})
复制代码
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
var cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
复制代码
响应方法 参考连接
app.route()
app.route('/')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
复制代码
var express = require('express')
var router = express.Router()
// 该路由使用的中间件 全部的路由都会走这里
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
复制代码
var express = require('express');
var app = express();
app.get('/',function(req,res,next){
res.end("Hello world");
})
app.use(logErrors)
app.use(clientErrorHandler)
app.use(errorHandler)
function logErrors (err, req, res, next) {
console.error(err.stack)
next(err)
}
function clientErrorHandler (err, req, res, next) {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' })
} else {
next(err)
}
}
function errorHandler (err, req, res, next) {
res.status(500)
res.render('error', { error: err })
}
app.listen(8081,function(){
console.log("接口已启动")
})
复制代码
express内置了一个错误处理句柄,它能够捕获应用种可能出现的任意错误。这个缺省的错误处理中间件将被添加到中间件堆栈的底部。
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
复制代码
npm install swig
<!doctype html>
<html> <head> <meta charset="utf-8"> <title>{% block title %}{% endblock %}</title> {% block head %} {% endblock %} </head> <body> {% block content %}{% endblock %} </body> </html> 复制代码
{% extends 'layout.html' %}
{% block title %}index {{title}} {%endblock%}
{% block head %}
{{title}}
{% endblock %}
{% block content %}
<p>This is just an awesome page.</p>
{% endblock %}
复制代码
var express = require("express");
var app = express();
var swig = require('swig');
app.set('view engine','html');
app.engine('html',swig.renderFile)
app.use(express.static("public"));
app.listen(8081,function(){
console.log("接口已启动")
})
app.get('/',function(req,res,next){
res.render('index',{
title:'首页'
})
})
复制代码
总结:
大概的了解了一下express 如何使用