cors 解决跨域

html 请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./jquery.min.js"></script>
</head>
<body>
<button id="btn">这里是cors解决跨域</button>


<script type="text/javascript">
    $('#btn').click(function () {
        $.ajax({
            url: 'http://localhost:3000/index',
            method: 'get',
            data: {name: 'zhangsan', age: 18},
            success: function (result) {
                console.log(result)
            },
            error: function (err) {
                console.log(err)
            }
        })
    })
</script>
</body>
</html>

 

js 解决跨域

let express = require('express')

let app = express()

app.get('/index', function (req, res) {
    // cors 添加请求头 端口是地址栏目前的端口是多少
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63342')
    let corsArr = [{name: 'zhangsan', age: 21}, {name: 'lisi', age: 20}]
    res.send(corsArr)
})

app.listen(3000, function (err) {
    if (err) console.log(err)
    else console.log('cors服务器启动成功')
})
posted @ 2022-07-21 15:55  生活在北极的企鹅  阅读(29)  评论(0编辑  收藏  举报