zoukankan      html  css  js  c++  java
  • Node.js第十三篇:koa框架处理跨域请求

    第一章:jsonp

    web01:服务端程序,端口80

    安装koa-jsonp模块:npm install koa-jsonp

    服务端程序中导入和配置jkoa-jsonp模块

    const koa = require('koa')
    const router = require('koa-router')()
    // 导入koa-jsonp模块
    const jsonp = require('koa-jsonp')
    
    const app = new koa()
    
    // 处理jsonp请求
    router.get('/list', async (ctx) => {
      // 接收回调函数名称
      let callbackName = ctx.query.callback || 'callback'
      // 返回jsonp
      ctx.body = callbackName + `(${JSON.stringify(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])})`
    })
    
    
    app.use(router.routes())
    app.use(router.allowedMethods());
    //配置 jsonp 的中间件 
    app.use(jsonp());
    
    app.listen(80)
    

    web02:前端程序,端口8080

      <button id="btn1">跨域-jsonp:发送异步请求</button>
      <script src="./jquery.js"></script>
      <script>
        // jsonp请求
        $('#btn1').click(function(){
          $.ajax({
            async:false,  
            url:'http://localhost/list',
            xhrFields: {widthCredentials:true},
            dataType: 'JSONP',
            success:function(data){
              console.log(data)
            }
          })
        })
     </script>
    

    第二章:CORS

    web01:服务端程序,端口80

    安装koa2-cors模块:npm insall koa2-cors

    配置和导入koa2-cors模块

    const koa = require('koa')
    const router = require('koa-router')()
    // 导入koa2-cors模块
    const cors = require('koa2-cors')
    
    const app = new koa()
    
    //配置 cors 的中间件 
    app.use(
      cors({
          origin: function(ctx) { //设置允许来自指定域名请求
              if (ctx.url === '/test') {
                  return '*'; // 允许来自所有域名请求
              }
              return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
          },
          maxAge: 5, //指定本次预检请求的有效期,单位为秒。
          credentials: true, //是否允许发送Cookie
          allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
          allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
          exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
      })
    )
    
    router.get('/list', async (ctx) => {
      ctx.body = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    })
    
    router.get('/test', async (ctx) => {
      ctx.body = 'test-ok';
    })
    
    
    app.use(router.routes())
    app.use(router.allowedMethods());
    
    app.listen(80)
    

    web02:前端程序,端口8080

    
      <button id="btn1">跨域-cors:发送异步请求1</button>
      <button id="btn2">跨域-cors:发送异步请求2</button>
      <script src="./jquery.js"></script>
      <script>
        // ajax请求
        $('#btn1').click(function(){
          $.ajax({
            url:'http://localhost/list',
            success:function(data){
              console.log(data)
            }
          })
        })
        // ajax请求
        $('#btn2').click(function(){
          $.ajax({
            url:'http://localhost/test',
            success:function(data){
              console.log(data)
            }
          })
        })
     </script>
    
  • 相关阅读:
    工作经常使用的SQL整理,实战篇(二)
    工作经常使用的SQL整理,实战篇(一)
    socket编程实例
    C# Socket编程笔记
    SQL Server中的事务与锁
    存储过程学习笔记(SQL数据库
    SQL Server 查询性能优化——创建索引原则(二)
    SQL Server 查询性能优化——创建索引原则(一)(转载)
    PSR-4——新鲜出炉的PHP规范
    PHPUNIT 单元测试
  • 原文地址:https://www.cnblogs.com/lpl666/p/12881119.html
Copyright © 2011-2022 走看看