当前位置:首页 > Windows程序 > 正文

通过HttpClient实现跟Nodejs API接口的数据交互

2021-03-29 Windows程序

一个简单的例子,通过HttpClient post数据来实现登陆nodejs的服务接口

nodejs: 使用expressjs + body-parser开发一个简单的login登陆服务接口

        

var express = require(‘express‘), bodyparser = require(‘body-parser‘); var app = express(); app.use(bodyparser.json({limit:‘1mb‘})); app.use(bodyparser.urlencoded({extended:true , limit:‘1mb‘})); //登陆接口> :3000/login app.post(‘/login‘ , function(req,res){ var username = req.body.username; var password = req.body.password; console.log(‘username:‘+ username +"; password:"+password); res.json({"message":‘welcome to login‘, ‘status‘:19999}); }); app.listen(3000, function(){ console.log(‘server is running‘); });

  

新建一个WPF工程,,在主窗体添加一个button按钮,然后编写button的click事件

  

private void _btnpost_Click_1(object sender, RoutedEventArgs e) {   HttpClient client = new HttpClient();  var postdata = new List< KeyValuePair< string ,string >>(); postdata.Add(new KeyValuePair<string,string>("username","vison")); postdata.Add(new KeyValuePair<string,string>("password","vison1987")); HttpContent content = new FormUrlEncodedContent( postdata); client.PostAsync(":3000/login",content).ContinueWith( (posttask) =>{ posttask.Result.Content.ReadAsStringAsync().ContinueWith((result) => { MessageBox.Show(result.Result.ToString()); //=>s输出json格式字符串{"message":‘welcome to login‘, ‘status‘:19999} }); posttask.Result.EnsureSuccessStatusCode(); }); }

=+ 测试完毕

通过HttpClient实现跟Nodejs API接口的数据交互

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69940.html