Express搭建服务遇到的跨域问题

背景

写Vue项目需要后台语言做响应请求,于是用node+express搭建一个服务用来做测试,出现了跨域问题

Access to XMLHttpRequest at 'http://localhost:3000/login' from origin 'null' has been blocked by COR

原来我搭建的node服务代码

const express = require('express')
const app = express()
const port = 3000



app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.post('/login', (req, res) => {
    const user = req.query
    console.log( req.query)
    if (user.mobile == '13709560002'){
        if (user.code == '1111'){
            res.header('Access-Control-Allow-Headers',['mytoken','Content-Type']);
            res.status(200).end('登陆成功')
            // res.send('登录成功',200)
        }else {
            res.send('密码错误')
        }
    }else {
        res.send('账号错误')
    }
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

后面发现这样写会出现跨域问题需要加入响应头,优化后的代码如下

const express = require('express')
const app = express()
const port = 3000

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.post('/login', (req, res) => {
    const user = req.query
    console.log( req.query)
    if (user.mobile == '13709560002'){
        if (user.code == '1111'){
            res.header('Access-Control-Allow-Headers',['mytoken','Content-Type']);
            res.status(200).end('登陆成功')
            // res.send('登录成功',200)
        }else {
            res.send('密码错误')
        }
    }else {
        res.send('账号错误')
    }
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

需要设置跨域资源共享响应头才可进行跨域响应

res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

饭一口口吃

来杯咖啡

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

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

打赏作者

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

抵扣说明:

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

余额充值