• Express写接口—接口的跨域问题-CORS中间件


    接口跨域问题:前面的POST和GET接口,存在一个不支持跨域问题

     使用在线版本的jqueryStaticfile CDNicon-default.png?t=M7J4https://www.staticfile.org/

    HTML+jquery ————>在这里的时候需要启动服务器

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Documenttitle>
    7. <script src="https://cdn.staticfile.org/jquery/3.6.1/jquery.min.js">script>
    8. head>
    9. <body>
    10. <button id="get">GETbutton>
    11. <button id="post">POSTbutton>
    12. <script>
    13. $(document).ready(function(){
    14. //1.测试GET接口
    15. $('#get').on('click',function(){
    16. $.ajax({
    17. type:'GET',//规定请求的类型(GET 或 POST)。
    18. url:'http://127.0.0.1/api/get',//规定发送请求的 URL
    19. data:{name:'zs',age:20},//规定要发送到服务器的数据。
    20. success:function(res){
    21. console.log(res)
    22. },
    23. })
    24. })
    25. //2.测试POST接口
    26. $('#post').on('click',function(){
    27. $.ajax({
    28. type:'POST',
    29. url:'http://127.0.0.1/api/post',
    30. data:{name:'白居易',age:80},
    31. success:function(res){
    32. console.log(res)
    33. },
    34. })
    35. })
    36. })
    37. script>
    38. body>
    39. html>

      from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.————————————说明接口存在跨域的问题

     当前协议是file,然后请求发送的url是http协议————只要协议、域名、端口号任何一个不同即不行

     解决跨域问题的主要方案是两种:

    CORS(主流方案,推荐使用)

    JSONP(有缺陷的解决方案:只支持GET请求)-——-

    ——或者直接设置响应头

     使用CORS中间件解决跨域问题

     CORS是Express的第三方中间件。通过安装和配置cors中间件,可以解决跨域问题

    运行:

    • npm install cors 中间件

    • 使用const cors=require('cors')导入中间件

    • 在路由之前调用app.use(cors())配置中间件,将其注册成为全局可可用的中间件

    创建api路由 

    1. //导入express
    2. const express=require('express')
    3. //创建路由对象
    4. const Router=express.Router()
    5. //定义get接口
    6. Router.get('/get',(req,res)=>{
    7. //通过req.query获取客户端通过查询字符串获取发送到服务器的数据
    8. const query=req.query //get请求使用req.query post请求使用req.body
    9. res.send(//服务器的响应
    10. {
    11. status:0,//0表示处理成功 1表示处理失败
    12. msg:'GET 请求成功!',//状态的描述
    13. data:query //响应给客户端的数据
    14. }
    15. )
    16. })
    17. //定义post接口
    18. Router.post('/post',(req,res)=>{
    19. //通过req.query获取客户端通过查询字符串获取发送到服务器的数据
    20. const body=req.body //get请求使用req.query post请求使用req.body
    21. res.send(//服务器的响应
    22. {
    23. status:0,//0表示处理成功 1表示处理失败
    24. msg:'POST 请求成功!',//状态的描述
    25. data:body //响应给客户端的数据
    26. }
    27. )
    28. })
    29. //向外导出路由
    30. module.exports=Router//之前={对象 对象里面是属性 可以做一个省略}

     创建服务器

    1. const express=require('express')
    2. //创建服务器
    3. const app=express()
    4. //配置解析表单数据的中间件
    5. app.use(express.urlencoded({extended:false}))
    6. const cors=require('cors')
    7. app.use(cors())
    8. //导入路由模块
    9. const router=require('./api路由模块')
    10. //把路由模块注册到app上 ——app.use作用注册全局中间件
    11. app.use('/api',router)//请求到达服务器 需要进行中间件的处理--挨个进行路由的匹配_统一前缀
    12. app.listen(80,()=>{
    13. console.log('express服务器启动成功 127.0.0.1')
    14. })

     

  • 相关阅读:
    树莓派PICO三种按键方式实现点灯!
    上海亚商投顾:沪指放量涨1.69% 房地产板块掀涨停潮
    谈谈Spring Cloud OpenFeign远程调用性能优化
    [超详细]SpringBoot整合WebSocket
    阿里云MQTT服务器搭建
    低轨互联网产业发展探究
    Html和Markdown中的空格, &nbsp; &ensp; &emsp; 以及 &thinsp; &zwnj; &zwj;三种Unicode空格
    Cave Cows 3
    部署WekaFS并行文件系统的10大理由
    小程序主题随接口而变
  • 原文地址:https://blog.csdn.net/weixin_47295886/article/details/126710819