跨域及CORS官方跨域

JSONP jsonp跨域的实现仅限于GET请求,不可用于POST 说明:实现的基本思路是利用html中script标签本身可跨域的特性,在发送请求时,在页面中创建script标签,追加到页面中。这实际上就像利用script标签引入外部资源 /*main.js*/ //申明handle函数 function handle(data) { //do something.... } ele.onclick = function () { //1.创建script标签 const script = document.createElement("script") //2.修改script的src属性 script.src = "http://127.0.0.1:8000/jsonP" script.id="tempScript"//添加id方便移除 //3.追加到页面中 document.body.appendChild(script) } /*server.js*/ app.get('/jsonP', (request, response) => { const data = { exist:1, msg:"用户名已经存在!" } let str = JSON.stringify(data) response.send(` handle(${str}); document.body.removeChild(document.querySelector("#tempScript")) `) }) 注意:response.send()/response.end()中利用ES6语法规范中的模板字符串直接返回一段js代码,script标签会自动解析并作用到页面上 CORS 如果要实现跨域,官方的解决方案是**CORS**,即通过设置CORS响应头实现跨域,这种跨域GET或POST请求均有效 //服务端设置响应头 app.all('/data', (request, response) => { response.setHeader('Access-Control-Allow-Origin', '*')//允许来自所有域的请求 response....

Aug 11, 2020 · 1 min · Archai