• 设置跨域访问


    前端页面:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div id="app">
            <ul>
                <li v-for="item in message">{{item}}</li>
            </ul>
        </div>
        <script src="https://unpkg.com/vue"></script>
        <script>
          const app = new Vue({
              el: '#app',
              data: {
                  message: [] 
              },
              created () {
                fetch('http://maoriaty.top/myjson/name') //model: cors默认权限跨域访问,需要服务端开启允许跨域访问,no-cors为无权限跨域访问,能拿到数据但不能使用
                  .then(Response => Response.json())
                  .then(data => this.message = data.name)
              }
          })
        </script>
    </body>
    </html>

    后端响应:

    const express = require('express');
    const app = express();
    
    app.all('*', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        res.header("X-Powered-By",' 3.2.1')
        res.header("Content-Type", "application/json;charset=utf-8");
        next();
    });
    
    app.get('/', (req, res) => res.send('this is json test interface'));
    app.get('/name', (req, res) => {
        let message = {
            name: ['jack', 'susan', 'maoriaty', 'jabin']
        }
        res.json(message);
    })
    
    const server = app.listen(3000, () => console.log(server.address().port));
  • 相关阅读:
    Team Foundation Sidekicks 2010
    Asp.net页面传值的方式汇总
    轻量级IOC框架Ninject使用
    AutoMapper使用简单总结
    页面请求的方式(Get与Post)
    总结2012 规划2013
    在reset css后两个input之间还是出现默认间隔的问题。
    js学习笔记事件委托
    程序猿工具——svn
    JS 事件添加onclick写法注意。
  • 原文地址:https://www.cnblogs.com/maoriaty/p/8422192.html
Copyright © 2020-2023  润新知