NodeJs builds a server locally, simulates interface requests, and obtains json data

created at 12-29-2021 views: 5

install node.js

First, you must install nodejs, if not, go to the node official website next Create a new folder where you see fit, enter the folder and open cmd or powershell to install express.

npm install -g express-generator@4

Create a project

Now the helloworld project appears under the express folder

express helloworld

Install dependencies

cd helloworld
npm install

start service

npm start

In this way, you can access http://localhost:3000 in the browser

Below is the content displayed in the browser


json file

Create a new json folder under the javascripts folder, and then create an index.json file under the folder, the content is as follows



Create a new index.js under the javascripts folder, the content is as follows

fetch("../json/index.json").then(function(res) {
if (res.ok) {
res.json().then(function(data) {
} else {
console.log("Looks like the response wasn't perfect, got status", res.status);
}, function(e) {
console.log("Fetch failed!", e);

Finally, open access to http://localhost:3000/json/index.json, you can see the following results

json data

If you want to put this json in other local server projects, the interface url is http://localhost:3000/json/index.json

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src=""></script>
            type: "GET",
            url: "http://localhost:3000/json/index.json",
            dataType: "json",
            success: function (res) {
            error: function (err) {


This will encounter a cross-domain problem, and the interface keeps going error


Find app.js, after all declarations, (about 11 lines) add the following code

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");

Then restart the server and try again, success!


Please log in to leave a comment.