基于Express框架使用POST传递Form数据

本文实例为大家分享了基于Express框架使用POST传递Form数据的具体代码,供大家参考,具体内容如下

客户端使用Form发送数据

在客户端Html文件中Form代码如下:

<!-- POST test -->
<form action="/test" method="post" id="foo" >
 <input type="text" name="username">
 <input type="password" name="password">
 <input type="submit">
</form>

在服务器端处理'/test' POST请求的代码如下:

var bodyParser = require('body-parser');

// ... 

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var 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数据,

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Post Data</title>
 <script src="jquery.min.js" type="text/javascript"></script>
 <script src="client.js" type="text/javascript"></script>
</head>
<body>

<!-- POST test -->
<form action='/update' method='post' id='foo' > Parameters
<table border="0">
 <tr>
 <td> File Name</td>
 <td> <input type="text" name="filename" value = "foo.txt" /></td>
 </tr>
</table>
</form>
<button name="button1" id='startButton' > Update</button>

</body>
</html>

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 parser
app.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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 浅谈Express.js解析Post数据类型的正确姿势

    一.概念介绍 1.POST请求:HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS.GET.HEAD.POST.PUT.DELETE.TRACE.CONNECT 这几种.其中 POST 一般用来向服务端提交数据. 2. Content-Type : 是指 http/https 发送信息至服务器时的内容编码类型, Content-Type 用于表明发送数据流的类型,服务器根据编码类型使用特定的解析方式,获取数据流中的数据.四种常见的 POST 请求的 Content-Type 数据

  • 基于node.js依赖express解析post请求四种数据格式

    node.js依赖express解析post请求四种数据格式 分别是这四种: www-form-urlencoded form-data application/json text/xml 1.www-form-urlencoded 这是http的post请求默认的数据格式,需要body-parser中间件的支持 服务器端的demo: var express = require('express'); var app = express(); var bodyParser = require('

  • 基于Express框架使用POST传递Form数据

    本文实例为大家分享了基于Express框架使用POST传递Form数据的具体代码,供大家参考,具体内容如下 客户端使用Form发送数据 在客户端Html文件中Form代码如下: <!-- POST test --> <form action="/test" method="post" id="foo" > <input type="text" name="username"&g

  • php基于jquery的ajax技术传递json数据简单实例

    本文实例讲述了php基于jquery的ajax技术传递json数据简单实现方法.分享给大家供大家参考,具体如下: html页面: <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <script type="text/javascript" src="jquery-1.8.2.mi

  • 搭建基于express框架运行环境的方法步骤

    一.Express简介 Express提供了一个轻量级模块,把Node.js的http模块功能封装在一个简单易用的接口中.Express也扩展了http模块的功能,使你轻松处理服务器的路由.响应.cookie和HTTP请求的状态.使用Express可以充当Web服务器. 二.搭建基于express框架运行环境  开发后端的node服务 1.安装express ① 安装全局变量 npm install express-generator -g (全局变量会在C盘node文件下) ②查看安装成功:e

  • node基于express框架操作Mysql数据库的步骤

    目录 一.在express项目中操作数据库的步骤 1.安装mysql模块 2.配置mysql模块 3.测试mysql模块能否正常工作 4.查询数据库数据 5.向数据库插入数据 6.更新数据库数据 7.更新数据库数据 8.删除数据库信息的标记删除 一.在express项目中操作数据库的步骤 ①安装操作 MySQL 数据库的第三方模块(mysql) ②通过mysql模块连接到MySQL 数据库 ③通过 mysql模块执行SQL语句 1.安装mysql模块 mysql模块是托管于npm 上的第三方模块

  • 从零开始学习Node.js系列教程之基于connect和express框架的多页面实现数学运算示例

    本文实例讲述了Node.js基于connect和express框架的多页面实现数学运算.分享给大家供大家参考,具体如下: 1.使用connect框架 .use方法用于绑定中间件到connect服务器,它会配置一系列在接到请求时调用的中间件模块,此例中我们要配置的中间件有favicon logger static router app.get/post/put        写法:app.requestName('path', function(req, res, next){}); app-co

  • form表单传递数组数据、php脚本接收的实例

    通过数组传递表单数据,可以保存数据之间的业务属性关系,比如有很多Student,每隔Student都有姓名.年龄.性别.爱好等表单信息.提交表单后还需要针对每个student进行处理或者保存.这样肯定需要为每个student的这些属性表单建立起关联关系,一种方式是根据属性表单的name上加特殊标记进行识别,但是数组传递表单就能使表单数据更结构化. 例子如下: <input type="hidden" name="msginfo[name][]" value=&

  • SpringMVC框架下JQuery传递并解析Json格式的数据是如何实现的

    json作为一种轻量级的数据交换格式,在前后台数据交换中占据着非常重要的地位.Json的语法非常简单,采用的是键值对表示形式.JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序,也可以从服务器端程序传递json格式的字符串给前端并由前端解释.这个字符串是符合json语法的,而json语法又是 javascript语法的子集,所以javascript很容易解释它,而且

  • jQuery基于ajax()使用serialize()提交form数据的方法

    本文实例讲述了jQuery基于ajax()使用serialize()提交form数据的方法.分享给大家供大家参考,具体如下: jQuery的serialize()方法通过序列化表单值,创建URL编码文本字符串,我们就可以选择一个或多个表单元素,也可以直接选择form将其序列化,如: <form action=""> First name: <input type="text" name="FirstName" value=&qu

  • php基于Fleaphp框架实现cvs数据导入MySQL的方法

    本文实例讲述了php基于Fleaphp框架实现cvs数据导入MySQL的方法.分享给大家供大家参考,具体如下: <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class Controller_KaoqinUpload extends FLEA_Controller_Action { var $uploaddir = "./uploa

  • Express无法通过req.body获取请求传递的数据解决方法

    目录 前言 1.问题描述 2. 解决办法 2.1 解决JSON内容格式 2.2.解决x-www-form-urlencoded内容格式 3.附 3.1.获取get请求参数 3.2.封装XMLHttpRequest 4.总结 前言 最近尝试重新封装XMLHttpRequest,在发post请求的时候,发现express通过req.body获取不到数据,req.body打印出来是一个空对象. 网上也试了网上各种办法,还是不成功,最后发现需要在XMLHttpRequest请求时设置一个请求头,来标识发

随机推荐