Node.js跨域

Node.js跨域,第1张

1.出现跨域

app.js:

const express = require("express");
const app = express();
const PORT = 3000;
app.get("/data", (req, res) => {
  res.send({ name: "张三", age: 12 }
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});

index.html:



  
    
    
    
    跨域的解决办法:JSONP
    
  
  
   
    
  

2.JSONP的解决方案一

app.js:

const express = require("express");
const app = express();
const PORT = 3000;
app.get("/data", (req, res) => {
  let data = { name: "张三", age: 12 };
  res.send(`callback(${JSON.stringify(data)})`);
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});

index.html:



  
    
    
    
    跨域的解决办法:JSONP
    
  
  
    

xxx的年龄是xxx

3.JSONP的解决方案二

app.js:

const express = require("express");
const app = express();
const PORT = 3000;
app.get("/data", (req, res) => {
   let data = { name: "张三", age: 12 };
   res.jsonp(data);
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});

index.html:



  
    
    
    
    跨域的解决办法:JSONP
    
  
  
    

xxx的年龄是xxx

4.$ajax 的JSONP的写法

app.js:

const express = require("express");
const app = express();
const PORT = 3000;
app.get("/data", (req, res) => {
   let data = { name: "张三", age: 12 };
   res.jsonp(data);
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});

index.html:



  
    
    
    
    跨域的解决办法:JSONP
    
  
  
   
    
  

5.后端解决跨域

app.js:

const express = require("express");
const app = express();
const PORT = 3000;
app.get("/data", (req, res) => {
  let data = { name: "张三", age: 12 };
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send(data);
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
const PORT = 3000;
app.get("/data", (req, res) => {
  let data = { name: "张三", age: 12 };
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send(data);
});
app.listen(PORT, () => {
  console.log(`服务器已经启动在${PORT}上`);
});

 index.html:



  
    
    
    
    跨域的解决办法
    
  
  
    

xxx的年龄是xxx

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/742824.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存