前端

  1. const funJsonp = (params) => { //将参数转为序列化字符串
  2. let temp = ''
  3. for (let i in params) {
  4. temp += i + '=' + params[i] + '&'
  5. }
  6. return temp
  7. }
  8. const defaultConfig = {
  9. callbackName: "jsonpCallback"
  10. }
  11. jsonp跨域
  12. const jsonp = (url, params, options = defaultConfig) => {
  13. // 返回一个可以链式调用的promise对象
  14. return new Promise((resolve, reject) => {
  15. //将前端传递querystring查询字符串的参数,拼接到地址栏
  16. url = url.indexOf("?") > -1 ? url + funJsonp(params) : url + '?' + funJsonp(params)
  17. url += `callback=${options.callbackName}`
  18. //动态创建script标记
  19. const script = document.createElement("script")
  20. //设置接口的请求地址
  21. script.setAttribute('src', url)
  22. //设置请求jsonp接口的回调函数
  23. window[options.callbackName]=result=>{
  24. //请求jsonp接口成功后,删除该函数 - 不污染window
  25. delete window[options.callbackName];
  26. //从页面中删除请求接口动态创建的script标记
  27. document.body.removeChild(script)
  28. if(result){
  29. resolve(result)
  30. }else{
  31. reject('服务器没有返回信息')
  32. }
  33. }
  34. //动态创建script标记,错误的监听
  35. script.addEventListener('error', () => {
  36. delete window['jsonpCallback'];
  37. document.body.removeChild(script);
  38. reject('服务器加载失败!');
  39. });
  40. document.body.append(script)
  41. })
  42. }
  43. //////ajax 跨域
  44. const request=(url,params,type='GET')=>{
  45. return new Promise((resolve,reject)=>{
  46. const xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft','XMLHTTP')
  47. if(type==='Get'&&params){
  48. url = url.indexOf("?") > -1 ? url + funJsonp(params) : url + '?' + funJsonp(params)
  49. xhr.open(type,url)
  50. xhr.send(null)
  51. }else if(type==='POST'){
  52. xhr.open(type,url)
  53. xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
  54. xhr.send(funJsonp(params))
  55. }
  56. xhr.onreadystatechange=()=>{
  57. if(xhr.readyState===4){
  58. if(xhr.status===200){
  59. resolve(JSON.parse(xhr.responseText))
  60. }else{
  61. reject(new Error('request failed!'))
  62. }
  63. }
  64. }
  65. })
  66. }
  1. <script src="./index.js"> </script>
  2. <script>
  3. request("http://localhost:3000/api",{username:'zhangsan',password:123},'Get').then(res=>{
  4. console.log(res)
  5. })
  6. request("http://localhost:3000/apiPost",{username:'zhangsan',password:13},'POST').then(res=>{
  7. console.log(res)
  8. })
  9. fetch("http://localhost:3000/api").then(res=>{
  10. return res.json()
  11. }).then(res=>{
  12. console.log(res)
  13. })
  14. jsonp("http://localhost:3000/api",{username:111,password:222}).then(res=>{
  15. console.log(res)
  16. }).catch(err=>{})
  17. </script>

后台

  1. module.exports.formatJsonp=(callbackName,params)=>{
  2. return callbackName+'('+JSON.stringify(params)+')'
  3. }
  1. app.get("/api",(req,res)=>{
  2. let {query}=url.parse(req.url,true)
  3. let {callback}=query
  4. console.log(query)
  5. const {formatJsonp}=require("./config")
  6. if(callback){
  7. res.writeHead(200,{'Content-Type':'text/javascript'})
  8. const result={code:1,type:"jsonp"}
  9. const data=formatJsonp(callback,result)
  10. res.end(data)
  11. }else{
  12. res.writeHead(200,{'Access-Control-Allow-Origin':"*"})
  13. res.end(JSON.stringify({code:1,type:"json"}))
  14. }
  15. })
  16. app.post("/apiPost",(req,res)=>{
  17. let data=req.body
  18. res.writeHead(200,{'Access-Control-Allow-Origin':'*'})
  19. res.end(JSON.stringify({code:1,methods:'post',type:"json",data}))
  20. })