您当前的位置: 首页 >  json

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

js:json请求和jsonp请求

彭世瑜 发布时间:2022-09-20 10:57:33 ,浏览量:3

请求方式同源检查解决方式json是服务端支持jsonp否不需要服务端支持

目录
    • 一、使用json请求
      • 1.1 未开启跨域
      • 1.2 开启跨域
    • 二、使用jsonp

一、使用json请求 1.1 未开启跨域

安装依赖

$ pnpm i express

服务端代码

// server.js
const express = require("express");

const app = express();

// 返回json数据
app.get("/api/json", (request, response) => {
  response.json({ msg: "ok" });
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server runing on http://127.0.0.1:${port}`);
});

启动服务端

$ node server.js
Server runing on http://127.0.0.1:5000

客户端依赖

$ pnpm i http-server

# 启动静态服务器
$ npx http-server -p 5500 -c-1

此时,后端服务器运行在5000 端口,前端静态服务器在运行在5500 端口

出现了跨域问题

前端访问地址:http://127.0.0.1:5500/index.html

接口地址:http://127.0.0.1:5000/api/json

发送json 请求

// script.js
fetch("http://127.0.0.1:5000/api/json")
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        console.log(data);
      });

直接显示跨域错误

Access to fetch at 'http://127.0.0.1:5000/api/json' 
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs, 
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
1.2 开启跨域

安装依赖

$ pnpm i cors

服务端代码

// server.js
const express = require("express");
var cors = require('cors')

const app = express();

// 开启跨域
app.use(cors())

// 返回json数据
app.get("/api/json", (request, response) => {
  response.json({ msg: "ok" });
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server runing on http://127.0.0.1:${port}`);
});

重启服务后,前端可以正常获取接口数据

二、使用jsonp

服务端代码

// server.js
const express = require("express");
// var cors = require('cors')

const app = express();

// 开启跨域
// app.use(cors())

// 返回json数据
app.get("/api/json", (request, response) => {
  response.json({ msg: "ok" });
});

// 返回jsonp数据
app.get("/api/jsonp", (request, response) => {
    response.jsonp({ msg: "ok" });
  });

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server runing on http://127.0.0.1:${port}`);
});

前端代码

// 动态导入script
function importScript(src) {
  var hm = document.createElement("script");
  hm.src = src;
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(hm, s);
}

// 全局的响应处理函数
function handleResponse(res) {
  console.log(res);
}

(function () {
  sendJsonpBtn.addEventListener("click", function () {
    importScript("http://127.0.0.1:5000/api/jsonp?callback=handleResponse");
    // jsonp的响应
    // /**/ typeof handleResponse === 'function' && handleResponse({"msg":"ok"});
  });
})();

不需要开启跨域就可以直接获取到数据了

参考 一分钟说完JSONP请求,面试满分答案ヾ(≧▽≦*)o

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0608s