前端页面:
<!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));