Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

express配置 #7

Open
yangkaiyangyi opened this issue Oct 9, 2018 · 0 comments
Open

express配置 #7

yangkaiyangyi opened this issue Oct 9, 2018 · 0 comments

Comments

@yangkaiyangyi
Copy link
Owner

yangkaiyangyi commented Oct 9, 2018

安装express模块

npm install express   可以参考Express官方文档

image
编写配置文件index.js,并执行

node index/node index.js
处理请求
处理GET请求:配合req.query
处理POST请求:需要body-parser模块,配合req.body
GET POST JSONP COOKIE
req.query req.body req.query req.cookies
//npm install express
var express = require('express');
//npm install body-parser
var bodyParser = require("body-parser");
var app = express();
//配置静态文件夹,在本地public读取css,js,html等文件
app.use(express.static('public'));
//post请求需要body-parser模块处理
app.use(bodyParser.urlencoded({
	extended: false
}));
app.get('/', function(req, res) {
	res.send('Hello World!');
});
app.get('/home', function(req, res) {
	//get请求参数对象
	console.log('get请求参数对象:', req.query);
	res.send('get请求');
});
app.post('/home', function(req, res) {
	//post请求参数对象
	console.log('post请求参数对象:', req.body);
	res.send('post请求');
});
var server = app.listen(3000, function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Example app listening at http://%s:%s', host, port);
});

匹配路由参数

app.get('/add/:id/:age', function(req, res) {
	//追加请求头
	res.append("Access-Control-Allow-Origin","*");
	//?id=xx&age=xxx
	console.log(req.query)
	//:id/:age
	console.log(req.params)
	res.send("Hello Oaoafly");
})

跨域
可在中间件中追加这句防止跨域

res.append("Access-Control-Allow-Origin","*");

模板文件
这个设置视图文件的放置地方,然后配置jade为其模板渲染引擎,这里也需要安装jade模块实现

//views, 放模板文件的目录,比如: 
app.set('views', './views')
//view engine, 模板引擎
app.set('view engine', 'jade'

然后安装对应的模板引擎npm包

npm install jade

然后创建一个views文件夹,并在里面新建一个xxxx.jade文件,内容如下

html helloworld

在中间件中添加如下关键代码,res.render("文件名可省略后缀",{需要渲染在模板上的数据})

app.get('/', function(req, res) {
	connection.query("select * from news",function(err,data){
	var content = "Hello Oaoafly";
	res.render("qianfeng",{
		//model
		name:'xie',
		name2:'lan',
		news:data
	    })
	})
	//res.send("<p style='color:red'>"+content+"</p>");
})

静态文件

Express提供了内置的中间件express.static来设置静态文件如:图片, CSS,JavaScript等

你可以使用express.static中间件来设置静态文件路径

例如,如果你将图片, CSS,JavaScript文件放在public目录下

在app.js根目录下创建一个public文件夹,然后在代码中添加

app.use(express.static('public'));

设置完静态文件夹后我们可以用res.sendFile(文件路径)方法来把文件发送到前端

注意路径要用绝对路径__dirname + "/public/" + "upload.html"

```app.get('/index.html', function (req, res) {
   res.sendFile(__dirname + "/public" + "index.html");
})

还有值得注意的一点就是,对于每个应用程序,可以有多个静态目录,比如你可以按上传的文件类型分目录,当我们找某张图片的时候就会从这几个静态文件夹中一起找取

app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));

连接数据库

连接数据库,可以安装mysql模块实现
var mysql = require("mysql");
var connection = mysql.createConnection({
		host: "localhost",
		user: "root",
		password: "",
		database: "asm"
})
//执行数据库连接 .close();
connection.connect();
app.post('/add', function(req, res) {
	//追加请求头
	res.append("Access-Control-Allow-Origin","*");
	console.log(req.body);
	connection.query("insert into news (title,text) values ('" + req.body.title + "','" + req.body.text + "')",function(err,data){
		console.log(data)
	})
	res.send("增加信息");
	
})

body-parser

npm install body-parser


var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json 
app.use(bodyParser.json())

cookie-parser

npm install cookie-parser

通过app.use()方法调用

var cookieParser = require('cookie-parser')
app.use(cookieParser())

然后在中间件中通过req.cookies获取前端页面的cookie,是一个通过处理的对象

@yangkaiyangyi yangkaiyangyi changed the title express配置1 express配置 Oct 10, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant