• 设置跨域访问


    前端页面:

    <!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));
  • 相关阅读:
    Beta 冲刺 (5/7)
    Beta 冲刺 (4/7)
    软件产品案例分析(团队)
    Beta 冲刺 (3/7)
    Beta 冲刺 (2/7)
    Beta 冲刺 (1/7)
    BETA 版冲刺前准备
    个人作业——软件工程实践总结作业
    Beta 答辩总结
    Beta 冲刺 (7/7)
  • 原文地址:https://www.cnblogs.com/maoriaty/p/8422192.html
Copyright © 2020-2023  润新知