vue-cli 中可以通過配置 proxyTable 解決開發(fā)環(huán)境的跨域問題,具體可以參考這篇文章:
Vue-cli proxyTable 解決開發(fā)環(huán)境的跨域問題
如果后端接口尚未開發(fā)完成,前端開發(fā)一般使用mock數(shù)據(jù)。
mock方法有多種多樣,這里給出兩種:
方法一: 使用express搭建靜態(tài)服務(wù)
mock數(shù)據(jù)寫在json文件中,proxyTable 里將接口代理到具體mock數(shù)據(jù)json文件上。
具體方法:
- 創(chuàng)建
mock
文件夾 -
build/dev-server.js
中添加如下代碼
npm run dev
啟動(dòng)后,可以通過 http://localhost:8080/mock/db.json 訪問數(shù)據(jù),proxyTable對應(yīng)設(shè)置代理即可(代理設(shè)置方法與解決跨域方法相似)
方法二 使用 JSON Server 搭建 Mock 服務(wù)器
JSON Server 是一個(gè)創(chuàng)建偽RESTful服務(wù)器的工具,具體使用方法可以看官方文檔,這里直接講在vue-cli 中的用法。
配置流程
- 全局安裝
$ npm install -g json-server
- 項(xiàng)目目錄下創(chuàng)建
mock
文件夾 -
mock
文件夾下添加db.json
文件,內(nèi)容如下
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
-
package.json
添加命令
"mock": "json-server --watch mock/db.json",
"mockdev": "npm run mock & npm run dev"
啟動(dòng) mock 服務(wù)器
$ npm run mock
命令 運(yùn)行 mock server
訪問 http://localhost:3000/
發(fā)現(xiàn) db.json
下第一級 json 對象被解析成為可訪問路徑
GET請求具體路徑 如:http://localhost:3000/posts 可獲取數(shù)據(jù)
faker.js 批量生成偽數(shù)據(jù)
如果需要大量的偽數(shù)據(jù),手動(dòng)構(gòu)造比較費(fèi)時(shí)費(fèi)力,可以使用 faker.js 批量生成。faker.js 的具體使用參見官方文檔,這里做一個(gè)示例。
-
$ cnpm install faker -G
全局安裝 faker -
mock
目錄下創(chuàng)建faker-data.js
,內(nèi)容如下
module.exports = function () {
var faker = require("faker");
faker.locale = "zh_CN";
var _ = require("lodash");
return {
people: _.times(100, function (n) {
return {
id: n,
name: faker.name.findName(),
avatar: faker.internet.avatar()
}
}),
address: _.times(100, function (n) {
return {
id: faker.random.uuid(),
city: faker.address.city(),
county: faker.address.county()
}
})
}
}
-
$ json-server mock/faker-data.js
在 json server 中使用 faker
請求 http://localhost:3000/address 可以獲取到隨機(jī)生成的100組偽數(shù)據(jù)
添加中間件
json server 使用 RESTful 架構(gòu),GET請求可以獲取數(shù)據(jù),POST 請求則是添加數(shù)據(jù)。
在開發(fā)過程中,有時(shí)候想直接模擬獲取POST請求返回結(jié)果,可以添加 express 中間件 將POST請求轉(zhuǎn)為GET請求。
-
mock
目錄下創(chuàng)建post-to-get.js
,內(nèi)容如下
module.exports = function (req, res, next) {
req.method = "GET";
next();
}
- 啟動(dòng)命令添加運(yùn)行中間件
--m mock/post-to-get.js
"mock": "json-server --watch mock/db.json --m mock/post-to-get.js",
重新啟動(dòng)服務(wù),POST請求就被轉(zhuǎn)換為GET請求了
其他需求也可以通過添加不同的中間件實(shí)現(xiàn)。
代理設(shè)置
在 config/index.js
的 proxyTable
將請求映射到 http://localhost:3000
代碼中添加請求以測試效果
$ npm run mockdev
啟動(dòng)帶mock 數(shù)據(jù)的本地服務(wù)
結(jié)果如下: