前端jsonp
vue-jsonp方式:
- 添加依赖:npm install vue-jsonp --save
- 在main.js中添加:
import VueJsonp from 'vue-jsonp' Vue.use(VueJsonp);
- 在组件中使用
jsonpFetch(){ const url = 'http://127.0.0.1:8081/jsonp'; this.$jsonp(url,{ }).then((data)=>{ console.log(data) }) }
详细用法请参考:https://github.com/LancerComet/vue-jsonp#readme
axios方式(建议采用CORS的方式)
- npm install jsonp --save
- 在组件中使用:
const axiosJsonp = require("jsonp"); jsonpFetch() { // const url = 'http://127.0.0.1:8081/jsonp'; // this.$jsonp(url,{ // }).then((data)=>{ // console.log(data) // }) axiosJsonp("http://127.0.0.1:8081/jsonp", null, (err, data) => { if (err) { console.error(err.message); } else { console.log(data); } }); }
后端
gin的jsonp的参数是callback,前端一般也是默认callback,后端也一定要用jsonp,换成json或者其他的话将不能获取数据:
// JSONP serializes the given struct as JSON into the response body.
// It add padding to response body to request data from a server residing in a different domain than the client.
// It also sets the Content-Type as "application/javascript".
func (c *Context) JSONP(code int, obj interface{}) {
callback := c.DefaultQuery("callback", "")
if callback == "" {
c.Render(code, render.JSON{Data: obj})
return
}
c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
}
func StartServer(){
r := gin.Default()
r.GET("/jsonp", func(context *gin.Context) {
context.JSONP(200,gin.H{
"message":"data",
})
})
r.Run(":8081") // listen and serve on 0.0.0.0:8081
}