express和json的调用

在express工程里,建立app.js

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

//数据接口
var newsdata=[{
        'id':'1',
        'title':'标题1',
        'link':'链接1',
        'content':'内容1',
        'typeid':'1'
    },
    {
        'id':'2',
        'title':'标题2',
        'link':'链接2',
        'content':'内容2',
        'typeid':'2'
    }

        ];
//全部数据
app.get('/newlist/all',function (req, res){
    res.status(200);
    res.json(newsdata);
});
//typeid为1的数据
app.get('/newlist/type1',function (req,res){
    res.status(200);
    res.json(newsdata.filter(function(q){
        return q && q.typeid=='1';
    }));
});
var server = app.listen(3000,function(){
    console.log("请在浏览器访问:http://localhost:3000/n");
});

node一下app.js后

访问:http://localhost:3000/newlist/all

访问:http://localhost:3000/newlist/type1

如果此文对你有难度,请看Express的入门实例>>

原文地址:https://www.cnblogs.com/tinyphp/p/4925099.html