基于Express框架使用POST传递Form数据
前端  /  管理员 发布于 4年前   717
本文实例为大家分享了基于Express框架使用POST传递Form数据的具体代码,供大家参考,具体内容如下
客户端使用Form发送数据
在客户端Html文件中Form代码如下:
在服务器端处理'/test' POST请求的代码如下:
var bodyParser = require('body-parser'); // ... // create application/json parservar jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parservar urlencodedParser = bodyParser.urlencoded({ extended: false }) // ... // // request from form of the html file// app.post('/test', urlencodedParser, function(req, res) { if (!req.body) return res.sendStatus(400); console.log('Username: ' + req.body.username); console.log('Password: ' + req.body.password); res.send('Welcome, ' + req.body.username); });
客户端使用Node.js发送数据
在客户端使用Node.js发送Form数据的代码
const http = require('http'); var data = { username: 'foo', password: "test" }; var postData = require('querystring').stringify(data); console.log( postData ); function form(){ var options = { method: "POST", host: "localhost", port: 80, path: "/test", headers: { "Content-Type": 'application/x-www-form-urlencoded', "Content-Length": postData.length } }; var body = ''; var request = http.request( options, function(res) { // show results console.log('STATUS: ' + res.statusCode); res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; console.log('BODY: ' + chunk); }); res.on('end', function(err) { console.log( ' complete.'); }); }); request.on("error", function(e) { console.log('upload Error: ' + e.message); }) request.write( postData ); request.end(); } form();
客户端使用jQuery发送数据
客户端使用jQuery的 $.ajax post数据,
Post Data
client.js
$(document).ready(function(){ //try joining the server when the user clicks the connect button $("#startButton").click(function () { var filename = $("#input[name=filename]").val(); $.ajax({ type: 'POST', url: "/update", // dataType: "jsonp", data: { "filename": filename} , jsonpCallback: 'callback', success: function (data) { // ... }, error: function (xhr, status, error) { console.log('Error: ' + error.message); }, }); });});
server端使用node.js解析数据
//// Modules var express = require('express'); var bodyParser = require('body-parser'); //// Global variables var app = express(); // body parserapp.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false })); /* POST /update listing. */app.post('/update', function(req, res, next) { // Checking require if (!req.body) return res.sendStatus(400); console.log('filename: ' + req.body.filename); res.redirect('./');});
参考文献:expressjs/body-parser
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号