使用node模拟前端接口

data.json文件:

{
	"students": [
		{
			"id": "1",
			"name": "张小三",
			"age": 18
		}, {
			"id": 2,
			"name": "张三",
			"age": 18
		}, {
			"id": 3,
			"name": "张小",
			"age": 18
		}, {
			"id": 4,
			"name": "张三",
			"age": 18
		}, {
			"id": 5,
			"name": "张三",
			"age": 18
		}, {
			"id": 6,
			"name": "张三",
			"age": 18
		}
	]
}

get.js文件:

var express = require('express');
var fs = require('fs')

var  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('/',function(req,res){
  	fs.readFile('./data.json',function(err,data){
  		if(err){
  			console.log(0);
  		}else{
  			res.send(JSON.parse(data))
  		}
  	})
  	
  })

app.listen(8020,function(){
	console.log(1);
});

getdata.html:



	
		
		
		
	
	
		
	
	

结果图:

你可能感兴趣的:(使用node模拟前端接口)