1.创建项目
bash
npm init -y
touch index.js
node index
npm install express --save
2.安装修改自动更新
bash
npm i nodemon -g
在package.json里加入:"dev:live": "nodemon ./src/app.ts"
json
{
"name": "express",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev:live": "nodemon ./src/app.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"express": "^4.21.0"
}
}
2.安装跨域和表单中间件
bash
npm i cors
npm i body-parser
3.编写index.js
javascript
// 导入express
const express = require('express');
// 创建Web服务器
const app = express();
//引入cors
const cors = require('cors');
app.use(cors());
// 引入body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 监听服务器
app.listen('8089', () => {
console.log('server started at 8089');
});
//监听一个/user的GET请求接口,并返回响应数据:
app.get('/user', async (req, res, next) => {
// res.send向客户端发送响应数据
res.send({
name: 'xiaoli',
age: 20,
gender: '男'
});
});
// 监听一个/user的POST请求接口,并返回响应数据:
app.post('/user', async (req, res, next) => {
// res.send向客户端发送响应数据
res.send('请求成功');
});