zoukankan      html  css  js  c++  java
  • nodejs 快速搭建接口

    对于刚开始不会node写接口和调用接口,可以通过这个清晰的初步了解到整个过程。
    1.在node官网https://nodejs.org/en/下载node.js
    2.在自己电脑中新建一个文件夹,例如:D:/node
    3.在该新建的文件夹中,打开命令行窗口(shift+右击) npminit创建package.json文件
    4.通过 npm install express –save 安装express模块,后面要用到的 

    5.在node文件夹中新建app.js文件,将下面的代码复制到app.js文件中

     1 var express = require('express');
     2 var app = express();
     3 
     4 //设置跨域访问
     5 app.all('*', function(req, res, next) {
     6     res.header("Access-Control-Allow-Origin", "*");
     7     res.header("Access-Control-Allow-Headers", "X-Requested-With");
     8     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
     9     res.header("X-Powered-By", ' 3.2.1');
    10     res.header("Content-Type", "application/json;charset=utf-8");
    11     next();
    12 });
    13 
    14 
    15 
    16 var questions = [];
    17 
    18 
    19 function createRandomItem(id) {
    20     var heroes = ['张三', '李四', '王五', '赵六', '钱七', '路人甲', '路人乙', 'bruse Lee'];
    21     return {
    22         id: id,
    23         name: heroes[Math.floor(Math.random() * 7)],
    24         age: Math.floor(Math.random() * 1000),
    25         saved: Math.floor(Math.random() * 10000)
    26     };
    27 
    28 }
    29 
    30 for (var i = 0; i < 10000; i++) {
    31     questions.push(createRandomItem(i));
    32 }
    33 
    34 //写个接口123
    35 app.get('/123', function(req, res) {
    36     res.status(200),
    37         res.json(questions)
    38 });
    39 
    40 //配置服务端口
    41 var server = app.listen(3000, function() {
    42 
    43     var host = server.address().address;
    44 
    45     var port = server.address().port;
    46 
    47     console.log('Example app listening at http://%s:%s', host, port);
    48 })

     每次修改完app.js后 需要重新启动

  • 相关阅读:
    个人介绍
    实验三
    第二次实验
    实验一
    ATM管理系统
    第二次作业
    实验四 决策树算法及应用
    实验三 朴素贝叶斯算法及应用
    实验二 K-近邻算法及应用
    实验一 感知器及其应用
  • 原文地址:https://www.cnblogs.com/yiyangl/p/10307485.html
Copyright © 2011-2022 走看看