跨域的解决方式
• 方法 1.后端解决跨域 CORS
(跨域资源共享)(在 server.js
中添加)
app.use("/", (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');
next()
})
• 方法 2.使用 JQuery
提供的 jsonp
网页中添加一个 script
元素,向服务器请求 json
数据,这种做法不受同源
策略的限制,服务器接收到请求后,把数据放在一个指定名字的回调函数里传递
回来
methods: {
getData () {
var self = this
$.ajax({
url: 'http://f.apiplus.cn/bj11x5.json',
type: 'GET',
dataType: 'JSONP',
success: function (res) {
self.data = res.data.slice(0, 3)
self.opencode = res.data[0].opencode.split(',')
}})}}
• 方法 3.proxyTable
解决跨域(项目使用 vue-cl
i 脚手架搭建)
在 vue.config.js
中中添写如下代码
proxy: {
'/api': {
target: 'http://localhost:3000/', //对应自己的接口
changeOrigin: true,
55
ws: true,
pathRewrite: {
'^/api': ''
}}}