基于express制作服务器
安装必要的包
npm i express
- 创建
app.js
文件 - 创建
router.js
路由文件
路由文件
router.js文件
const express = require('express');
const rouder =express.Router();
rouder.get('/user/list',(req,res)=>{
res.send({
status:200,
data:[
{id:01,title:'demo1'},
{id:02,title:'demo2'},
{id:03,title:'demo3'},
]
});
})
rouder.post('/user/add',(req,res)=>{
res.send({
status:200,
success:'post发送成功',
});
})
rouder.post('/user/posform',(req,res)=>{
const query = req.body
//post请求返回的数据使用body接收,但是也要配置全局中间件对表单数据进行解析
res.send({
status:200,
success:'post发送成功',
data:query
});
})
// 暴露路由模块
module.exports = rouder;
app.js文件
内置的表单转换中间件
// 配置中间件
// 通过express.json()解析表单中的json格式数据
app.use(express.json());
// 通过express.urlencoded()解析表单中的url-encoded格式的数据
app.use(express.urlencoded({ extended: false }));
第三方中间件
// 1.导入解析表单数据的中间件
const parser = require('body-parser');
// 2.使用app.use()注册中间件
app.use(parser.urlencoded({ extended: false }))
app文件
const express = require('express')
const app = express()
const path = require('path');
// 导入路由模块
const router=require('./02-路由模块')
// 1.导入解析表单数据的中间件
const parser = require('body-parser');
// 2.使用app.use()注册中间件
app.use(parser.urlencoded({ extended: false }))
// 挂载静态资源
app.use('/', express.static(__dirname + '/public'));
// 解决跨域问题---------------------------------------------------
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Origin,Accept,X-Requested-With');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS.PUT,PATCH,DELETE');
res.header('X-Powered-By', '3.2.1');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
// --------------------------------------------------------------
// 使用这个路由全局中间件
app.use(router);
app.listen(8080, () => {
console.log(`Example app listening on port http://localhost:8080`)
})
静态资源文件index.html
存放在public文件夹下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
<h1>hello Express!</h1>
<button class="get">GET请求</button>
<button class="post">POST请求</button>
<form action="/user/posform" method="get" id="f1" target="_blank">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">发送</button>
</form>
<script>
$('.get').click(function () {
$.ajax({
type: "GET",
url: "http://192.168.210.146:8080/user/posform/user/list",
success: function (response) {
console.log(response);
}
});
})
$('.post').click(function () {
$.ajax({
type: "GET",
url: "http://192.168.210.146:8080/user/posform/user/add",
success: function (response) {
console.log(response);
}
});
})
// 获取页面已有的一个form表单
$('#f1').on('submit', function (e) {
// 第二种阻止表单默认提交行为(跟第一种一样)
e.preventDefault();
// 利用serialize()获取表单中的所有数据
// 前提是被获取表单必须有name属性
// serializeArray()也可以获取表单中的数据
let shujv = $(this).serialize();
$.post('http://192.168.210.146:8080/user/posform',
shujv, function (res) {
console.log(res);
});
});
</script>
</body>
</html>
使用CORS解决跨域问题
可以使用CORS这个第三方包解决跨域问题,其实还有另一种解决方案JSONP,但后者仅支持GET请求
- 运行
npm install cors
安装中间件 - 使用
const cors = require('cors')
导入中间件 - 在路由之前调用
app.use(cors())
配置中间件
const express = require('express')
const app = express()
const path = require('path');
// 导入路由模块
const router=require('./02-路由模块')
// 1.导入解析表单数据的中间件
const parser = require('body-parser');
// 2.使用app.use()注册中间件
app.use(parser.urlencoded({ extended: false }))
// 解决跨域---------------------------------------------------
// 在路由之前配置cors
const cors=require('cors');
app.use(cors());
// ----------------------------------------------------------
// 挂载静态资源
app.use('/', express.static(__dirname + '/public'));
// 使用这个路由全局中间件
app.use(router);
app.listen(8080, () => {
console.log(`Example app listening on port http://localhost:8080`)
})