1、cors解决跨域
npm i cors
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
相当于res.header(‘Access-Control-Allow-Origin’, ‘*’)
const express = require('express')
const router = express.Router()
router.post('/login', (req, res) => {
res.header('Access-Control-Allow-Origin', '*')
body = req.body
res.send({
code: 0,
body
})
})
module.exports = router
2、jsonp解决跨域问题
script标签中的src属性请求url不存在跨域问题,所以可以用接口传递函数拿到服务端的数据
前端代码
<!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>Document</title>
</head>
<body>
<div>请求接口</div>
<script>
function getData(data) {
console.log(data)
}
</script>
<script src="http://127.0.0.1:3000/course/findCourse?callback=getData">
</script>
<!-- <script>
document.getElementsByTagName('div')[0].onclick = () => {
console.log('click')
axios.post('http://127.0.0.1:3000/user/login').then(res => {
console.log(res)
})
}
</script> -->
</body>
</html>
后端代码
const express = require('express')
const router = express.Router()
router.get('/findCourse', (req, res) => {
// res.header('Access-Control-Allow-Origin', '*')
const getData = req.query.callback
const data = {name: '老王'}
res.send(`${getData}(${JSON.stringify(data)})`)
})
module.exports = router