客户端使用FormData()封装表单后,后台使用Body-parser中间件,req.body里并没有表单中的数据。 - CNode技术社区

客户端使用FormData()封装表单后,后台使用Body-parser中间件,req.body里并没有表单中的数据。
发布于 10 年前 作者 fatbone008 5039 次浏览 最后一次编辑是 9 年前 来自 问答

前台页面代码:

<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script>
	 function submitData(){
		 var form=document.getElementById('form1');
		 var formData=new FormData(form);
		 var xhr=new XMLHttpRequest();
		 xhr.open('POST','14-23.html',true);
		 xhr.onload=function(e){
			 if(status=200){
				 document.getElementById('result').innerHTML=this.response;
			 }
		 };
		 xhr.send(formData);
	 }
 </script>
</head>
<body>
<form id="form1">
 姓:<input id="txtFirstName" name="firstname" type="text" value="陈">
 名: <input type="text" id="txtUserName" name="username" value="贻辉">
 <input type="button" value="提交" onclick="submitData();">
</form>
<output id="result"></output>
</body>
</html>

后台代码: /**

  • Created by chenyihui on 16/3/14. */
 var express=require('express');
 var fs=require('fs');
 var app=express();
 var bodyParser=require('body-parser');
 var mongo=require('mongodb');
 var server=mongo.Server('localhost','27017',{auto_reconnect:true})
 var db=mongo.Db('node-mongo-example',server,{safe:true});
 
 app.use(bodyParser.urlencoded({extended:false}));
 app.use(bodyParser.json());
 
 
 app.get('/14-23.html',function(req,res){
 res.sendFile(__dirname+'/14-23.html');
 });
 app.post('/14-23.html',function(req,res){
 db.open(function(err,db){
	 if(err) console.log('数据库链接成功');
	 else{
		 var str;
		 db.collection('users', function (err,collection) {
			 collection.insert({'username':req.body.username,'firstname':req.body.firstname},function(err,docs){
				 if(err) var str='数据库插入数据失败';
				 else{
					 str='数据插入成功:'+docs;
				 }
				 db.close();
				 res.send(str);
			 });
		 })
	 }
 });
 });
 app.listen(1337,'127.0.0.1');

req.body.username和req.body.firstname都为null req.body这个对象倒是存在。 我试过不使用FormData(),而只将form里的button改为sumbit,加个post方法,直接提交,就可以接收到这两个数据。 求大神指导,是formData的问题吗?

回到顶部

AltStyle によって変換されたページ (->オリジナル) /