Node.js Express 中间件跨域处理 Get及Post请求 JSON参数接收 文件上传

Express框架

Express‌,基于Node.js的轻量级、灵活的Web应用框架,它提供了一系列强大的功能,帮助开发者快速构建Web应用和API。

Express,设计理念是提供最小的核心功能,并通过中间件和路由机制,使得开发者可以根据需要扩展其功能‌。

Express项目案例

环境: Windows11 + NodeJS18.12.1

创建项目: mkdir express-project,cd express-project,npm init -y

安装express: npm install express

安装cors跨域:npm install cors

安装文件上传:npm install express-fileupload

新建文件: index.js

const express = require('express');
const cors = require('cors');
const app = new express();
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
// const app = express()
const port = 3000;

// 跨域处理
app.use(new cors());

// 使用 express.urlencoded() 中间件
app.use(express.urlencoded({ extended: true }));
// 使用body-parser中间件解析JSON
app.use(bodyParser.json());
// 中间件,用于处理文件上传
app.use(fileUpload());

// get请求
app.get('/',function(req,res){
    res.send('hello world!');
});

// get请求,返回JSON
app.get('/json',function(req,res){
    const data = {
        name: 'guguaijinren',
        age: 38,
        email: 'hello@example.com'
    };
    res.send(data);
});

// get请求,并接收参数(URL传递参数)
app.get('/getParams',(req,res)=>{
    console.log("req.query",req.query);
    res.send(req.query);
});

// post请求,并接收参数(x-www-form-urlencoded)
// 使用express.urlencoded()中间件
app.post('/submit1', (req, res) => {
    // 获取POST请求参数
    const postData = req.body;
    console.log("postData", postData);
    res.send(postData);
});

// post请求,并接收参数(JSON参数)
// Express 4.16版本及以上,body-parser已经集成到了Express
app.post('/submit2', (req, res) => {
    // 获取POST请求参数
    const postJsonData = req.body;
    console.log("postJsonData",postJsonData);
    res.send(postJsonData);
});

// 文件上传
app.post('/upload', (req, res) => {
    if (!req.files || Object.keys(req.files).length === 0) {
      return res.status(400).send('No files were uploaded.');
    }
    console.log('req.files',req.files)
    let uploadedFile = req.files.file;
    // 使用`mv`方法将文件保存到硬盘上的指定目录
    uploadedFile.mv('./' + uploadedFile.name, function(err) {
        if (err) {
            return res.status(500).send(err);
        }
        res.send('File uploaded!');
    });
  });

// 监听
app.listen(port,()=>{
    console.log(`Server is running on port ${port}.`)
});

修改package.json文件,scripts下添加: "serve": "node index.js",

运行: npm run serve

访问地址: http://127.0.0.1:3000/

项目测试

POST,x-www-form-urlencoded传递参数。

POST,body的application/json格式传递参数。

POST文件上传。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

古怪今人

您的鼓励将是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值