• node.js创建简单服务测试请求数据


    工具:安装node;

    1,创建文件夹 server,

    2 ,在server文件夹下分别创建server.js 和 package.json 文件

    3,server.js 代码:

     1 var express = require('express');
     2 var app=express();
     3 
     4 app.all('*', function(req, res, next) {
     5     res.header("Access-Control-Allow-Origin", "*");
     6     res.header("Access-Control-Allow-Headers", "X-Requested-With");
     7     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
     8     res.header("X-Powered-By",' 3.2.1');
     9     res.header("Content-Type", "application/json;charset=utf-8");
    10     //res.header("Content-Type", "text/plain;charset=utf-8");
    11     //res.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    12     next();
    13 });
    14 
    15 var bodyParser = require('body-parser');
    16 
    17 app.use(bodyParser.json());
    18 app.use(bodyParser.urlencoded({ extended: false }));
    19  
    20 // get请求地址: localhost:3000
    21 app.get('/',function(req,res){ 
    22     res.send('首页');
    23    // res.json({"msg":'get请求成功!'});
    24 })
    25 
    26 var numb=0;
    27 // post请求地址: localhost:3000/post
    28 app.post('/post',function(req,res){
    29     console.log(req.body, numb);
    30      res.json({"msg":'post请求成功' + numb++});
    31 })
    32 
    33 // get请求地址: localhost:3000/jsonp
    34 app.get('/jsonp',function(req,res){
    35     //console.log(req.body);
    36     res.jsonp({"msg":'这是jsonp请求'});
    37 
    38 })
    39 
    40 app.listen(3000,'127.0.0.1');

    4, package.json代码:

    1 {
    2   "dependencies": {
    3     "ejs": "^2.5.6",
    4     "express": "^4.15.3",
    5     "socket.io": "^2.0.3",
    6     "body-parser": "~1.17.1"
    7   }
    8 }

    5,打开终端cd到server文件夹目录下,运行 npm install

    6, 依赖安装完成后运行 node ./server.js

    7, 打开浏览器,地址栏输入localhost:3000 ; 回车页面显示 “首页” 两个字, 服务成功运行。

  • 相关阅读:
    创建二叉树
    并查集
    opn模块
    【ES6】map、reduce、filter、sort、箭头函数、class继承、yield
    css应用视觉设计
    json解决ajax跨域的原理
    flex盒子布局
    前后台交互ajax请求模块
    react后台项目开发(一)
    高阶函数&&高阶组件(二)
  • 原文地址:https://www.cnblogs.com/zhenguo-chen/p/10447740.html
Copyright © 2020-2023  润新知