express+cors模拟解决跨域
模拟写的node服务器请求
const express = require('express') const app = express() app.get('/api/getname', (req, res) => { res.send({ name: '黎明', age: 18 }) }) app.listen(3000, () => { console.log('connect host3000') })
使用客户端访问请求
import axios from 'axios' let host = 'http://127.0.0.1:3000' let url = host + '/api/getname' axios.get(url).then(res => {console.log(res)})
启动项目报错
Access to XMLHttpRequest at 'http://127.0.0.1:3000/api/getname' from origin 'http://localhost:8070' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
跨域问题,在node项目安装cors
cnpm i cors -S
修改express配置
const express = require('express') const app = express() const cors = require('cors') app.use( cors( ) ) app.get('/api/getname', (req, res) => { res.send({ name: '黎明', age: 18 }) }) app.listen(3000, () => { console.log('connect host3000') })
重新启动项目,可以访问接口数据
如果配置cors后还是报跨域错误,或者提示has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes
检查一下请求路径是否与服务器路径一致,清空浏览器缓存在试,一般没有问题