码迷,mamicode.com
首页 > Windows程序 > 详细

node.js+express,实现RESTful API

时间:2015-07-09 17:30:56      阅读:445      评论:0      收藏:0      [点我收藏+]

标签:

node代码如下(exptest.js):

var express = require(‘express‘);
var bodyParser = require(‘body-parser‘);
var app = express();
var patientinfo=require(‘./node_entity/patientinfo‘);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded


app.get(‘/api/patientinfo‘,patientinfo.get);
app.post(‘/api/patientinfo‘,patientinfo.update);
app.put(‘/api/patientinfo‘,patientinfo.put);
app.delete(‘/api/patientinfo‘,patientinfo.delete);

app.listen(3000);

patientinfo.js(位于node_entity目录下,可自定义)代码如下:

exports.get = function(req, res){  

  res.setHeader(‘Content-Type‘, ‘application/json;charset=utf-8‘);  
  res.send(‘get patientinfo info ok‘); 
  console.log(‘遍历参数:‘); 
  for(var key in req.query)
          console.log(‘%s = %s‘,key,req.query[key]);
  console.log(‘patientinfo get ok!‘); 
};  
  
  
exports.delete = function(req, res){  
  res.setHeader(‘Content-Type‘, ‘application/json;charset=utf-8‘);  

  res.send({status:"success", message:"delete patientinfo success"});  
  console.log(‘遍历参数:‘); 
  for(var key in req.body)
          console.log(‘%s = %s‘,key,req.body[key]);
  console.log(‘patientinfo delete ok!‘);  
};  
  
  
exports.update = function(req, res){  
  res.setHeader(‘Content-Type‘, ‘application/json;charset=utf-8‘);  
 
  res.send({status:"success", message:"update patientinfo success"});  
  console.log(‘遍历参数:‘); 
  for(var key in req.body)
          console.log(‘%s = %s‘,key,req.body[key]);
  console.log(‘patientinfo update ok!‘);  
};  
  
  
exports.put = function(req, res){  
  res.setHeader(‘Content-Type‘, ‘application/json;charset=utf-8‘);  
  console.log(req.body);  

  res.send({status:"success", message:"add patientinfo success"});  
  console.log(‘遍历参数:‘); 
  for(var key in req.body)
          console.log(‘%s = %s‘,key,req.body[key]);
  console.log(‘patientinfo put OK!‘);  
};

 

通过C#编写一个winform程序,代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       
        enum Method
        {
            POST,
            GET,
            PUT,
            DELETE
        }
        private string MyWebRequest(string webUrl,Method method, IDictionary<string, string> parameters, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                string paramData = "";
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                        }
                        i++;
                    }

                    paramData = buffer.ToString();
                }
                if (method == Method.GET)
                {
                    webUrl += "?" + paramData;
                }
                
                

                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(webUrl));
                webReq.Method = method.ToString();
                webReq.ContentType = "application/x-www-form-urlencoded";
                //webReq.ContentType = "text/html";
                if (method != Method.GET)
                {
                    byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                    webReq.ContentLength = byteArray.Length;
                    Stream newStream = webReq.GetRequestStream();
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                }
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                // ret = HttpUtility.UrlDecode(ret);
                sr.Close();
                response.Close();
                


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ret;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param["Function"] = "StudioList";
            param["UserJID"] = "windows01@win-nq66026cp12";
            string ret = MyWebRequest("http://127.0.0.1:3000/api/patientinfo", Method.POST, param, Encoding.UTF8);

            MessageBox.Show(ret);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param["Function"] = "StudioList";
            param["UserJID"] = "windows01@win-nq66026cp12";
            string ret = MyWebRequest("http://127.0.0.1:3000/api/patientinfo",Method.DELETE, param, Encoding.UTF8);

            MessageBox.Show(ret);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param["Function"] = "StudioList";
            param["UserJID"] = "windows01@win-nq66026cp12";
            string ret = MyWebRequest("http://127.0.0.1:3000/api/patientinfo",Method.PUT, param, Encoding.UTF8);

            MessageBox.Show(ret);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param["Function"] = "StudioList";
            param["UserJID"] = "windows01@win-nq66026cp12";
            string ret = MyWebRequest("http://127.0.0.1:3000/api/patientinfo",Method.GET, param, Encoding.UTF8);

            MessageBox.Show(ret);
        }
    }
}

WinForm程序运行界面如下:

技术分享

在Windows命令窗口运行node exptest.js,然后依次点击WinForm程序上的按钮,结果如下:

技术分享

node.js+express,实现RESTful API

标签:

原文地址:http://www.cnblogs.com/sfcyyc/p/4633534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!