结合 express 实现jsonp跨域请求和post跨域请求

该项目展示了如何使用Node.js的Express框架处理前端的JSONP和POST请求,以及跨域问题。当禁用CORS时,仅JSONP请求能成功,而启用CORS后,两种请求方式均可正常工作。前端部分包含HTML和JavaScript,通过创建动态脚本标签进行JSONP请求,以及使用fetchAPI发送POST请求。
摘要由CSDN通过智能技术生成

项目目录

在这里插入图片描述

后端代码

首先安装依赖:npm i express cors
/server.js

const express = require('express');
const cors = require('cors');
const https = require('https');
const app = express();

//解决跨域
// app.use(cors());

//获取post请求的参数
app.use(express.json());

//jsonp 请求
app.get('/jsonp', (req, res) => {
    console.log(req.url);
    console.log(req.query);
    getText((data) => {
        res.send(req.query.callback + '(' + JSON.stringify({
            code: '0',
            msg: data
        }) + ')')
    });
})

//post 请求
app.post('/getData', (req, res) => {
    console.log(req.url);
    console.log(req.body);
    getText((data) => {
        res.send({
            code: '0',
            msg: data
        });
    });
})

function getText(fn) {
    //发送请求
    https.get('https://api.uixsj.cn/hitokoto/get?type=social', (data) => {
        var body = [];
        data.on('data', (chunk) => {
            body.push(chunk);
        });
        data.on('end', () => {
            body = Buffer.concat(body);
            fn(body.toString())
        });
    });
}

app.listen('7777', () => {
    console.log('后端启动在7777端口');
})

前端代码

/index.html

<!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>jsonp</title>
    <style>
        body,
        button {
            font-size: 30px;
            text-align: center;
        }
        
        button {
            cursor: pointer;
        }
        
        div {
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <button onclick="getJsonpData()">jsonp获取</button>
    <button onclick="getData()">post获取</button>
    <div id="div" style="color: pink;"></div>

    <script>
        const div = document.getElementById('div');
        const ip = 'http://localhost:7777';

        function show(data) {
            if (data.code === '0') {
                div.innerText = data.msg;
            }
        }

        function getJsonpData() {
            const body = document.querySelector('body');
            const script = document.createElement('script');
            script.src = ip + '/jsonp?name=摸鱼&callback=show';
            body.appendChild(script);
        }

        function getData() {
            fetch(ip + '/getData', {
                method: 'post',
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify({
                    a: 1
                })
            }).then(res => res.json()).then(res => {
                show(res);
            })
        }
    </script>
</body>

</html>

项目运行及页面展示

1、利用live-server等插件以服务器方式启动前端页面
2、使用 node server.js 启动后端代码

如果后端代码注释了解决跨域 app.use(cors()); 这句话,那么只有jsonp请求正常,post请求会报跨域错误:
在这里插入图片描述
如果解开 app.use(cors()); ,则两种方式都可以正常请求
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值