本身在作個vue
小demo的時候,想模擬從服務器獲取json
數據的過程,一開始的想法是使用fetch
直接獲取本地的json
文件,不管是install
了json-loader
仍是把json
文件放在index.html
的目錄下或webpck.config.js
裏output
的目錄下,可是fetch
一直報找不到文件。而後決定用fetch
向express
服務器發送請求,由服務器返回json
數據。html
先寫一個簡單的express
服務器,只有一個接口,起到示例做用就好了。back.js
以下:vue
var express = require('express') var app = express(); var allowCrossDomain = function(req, res, next) {//設置response頭部的中間件 res.header('Access-Control-Allow-Origin', 'http://localhost:8089');//8089是vue項目的端口,這裏至關於白名單 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Credentials','true'); next(); }; app.use(allowCrossDomain); app.get("/api/data",function (request,response) { var data = require('./grid.json');//要獲取的json文件 response.send(data); }) app.listen('3000',function () { console.log('>listening on 3000') });
而後使用命令node back.js
就能夠運行這個服務了。node
用語接受請求的服務器已經運行起來了,接下來就是使用fetch
來發送請求了,以下代碼段就能夠完成請求功能:web
fetch( "http://localhost:3000/api/data") .then(res=>res.json()) .then(data=>console.log(data)) .catch(function (e) { console.log('oops! error:',e.message) })
此時就能夠順利獲取想要的json數據了express