• 设置跨域访问


    前端页面:

    <!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));
  • 相关阅读:
    To be a master II.
    To be a master.
    快速排序
    选择排序
    冒泡排序
    Myeclipse 2013 Pro 激活工具
    Java多线程
    设计模式:动态代理
    面向对象
    新安装mysql修改密码,远程访问授权
  • 原文地址:https://www.cnblogs.com/maoriaty/p/8422192.html
Copyright © 2020-2023  润新知