Sharing tips on using express and fetch to obtain local json files in vue

小云云
Release: 2018-01-25 11:43:15
Original
2332 people have browsed it

This article mainly introduces the detailed explanation of using express+fetch to obtain local json files in vue. It is of great practical value. Friends in need can refer to it. I hope it can help everyone.

When I was making a small vue demo, I wanted to simulate the process of obtaining json data from the server. The initial idea was to use fetch to directly obtain the local json file, regardless of whether json-loader was installed Or put the json file in the directory of index.html or the directory of output in webpck.config.js, but fetch keeps reporting that the file cannot be found. Then decide to use fetch to send a request to the express server, and the server will return json data.

express server

First write a simple express server with only one interface, which can be used as an example. back.js is as follows:


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') });
Copy after login

Then use the command node back.js to run the service.

fetch to get json data

The server that accepts the request is already running. The next step is to use fetch to send the request. The following code snippet can complete the request function. :


fetch( "http://localhost:3000/api/data") .then(res=>res.json()) .then(data=>console.log(data)) .catch(function (e) { console.log('oops! error:',e.message) })
Copy after login

Now you can successfully obtain the json data you want

Related recommendations;

How jQuery can read local json files

JQuery uses ajax to read local json files

json file definition and usage summary

The above is the detailed content of Sharing tips on using express and fetch to obtain local json files in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!