创建Express后端项目

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('请求成功');
});
相关推荐
Jackson__9 分钟前
谈一下 css 隐藏陷阱,margin 塌陷问题
前端·css
奇舞精选9 分钟前
前端开发中常见的 SEO 优化
前端·seo
奇舞精选9 分钟前
使用cursor和claude-3.7实现吉卜力风格的页面
前端
白鸽(二般)26 分钟前
HTML、CSS、JavaScript
前端·css
大强的博客1 小时前
《Vue Router实战教程》22.导航故障
前端·javascript·vue.js
会蹦的鱼1 小时前
知识了解02——了解pnpm+vite+turbo+monorepo的完整构建步骤(react子项目)
前端·javascript·react.js
@PHARAOH1 小时前
HOW - 如何测试 React 代码
前端·react.js·前端框架
涵信1 小时前
第三节:React 基础篇-React组件通信方案
前端·javascript·react.js
90后的晨仔1 小时前
Flutter 报错 [☠] Network resources (the doctor check crashed)xxxx
前端·flutter