我在node.js中创建了一个非常简单的API,用于获取发布的数据。我正在使用javascript的xhr(xml http request)发送表单数据。(未使用jquery)但是我无法在服务器端接收表单数据。请帮助我解决此问题。下面是代码。
前端代码:
<form>
<input type="email" class="form-control" id="email"
placeholder="Enter email" name="email"
<input type="password" class="form-control" id="password"
placeholder="Enter password" name="password" required="">
<input type="file" class="form-control" id="userfile" name="userfile"
required="">
<button type="submit" class="btn btn-default" id="submit">Submit</button>
</form>
<script>
document.getElementById('submit').addEventListener('click',function(){
var email=document.getElementById('email').value;
var password=document.getElementById('password').value;
var fileInputElement = document.getElementById('userfile');
var formData = new FormData();
formData.append("email", email);
formData.append("password", password);
formData.append("userfile", fileInputElement.files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/form_submit");
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhr.send(formData);
})
</script>
后端代码(Node js API代码):
var express = require('express');
var app = express();
app.get('/',(req,res)=>{
console.log('you are welcome');
})
app.post('form_submit',function(req,res){
console.log('entered in post request');
console.log(req.body);
})
app.listen(3000,()=>{
console.log('connected to 3000 port');
})
答案 0 :(得分:0)
要允许express处理表单数据,您需要使用bodyParser模块:
将bodyParser.urlencoded()中间件用作:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
//Now you can get the form values will be on req.body:
app.post('form_submit',function(req,res){
console.log('entered in post request');
console.log(req.body);
})
仅供参考:请注意,body解析器不能处理多部分主体,因此在这种情况下,您可以使用类似multer
的模块Multer是用于处理multipart / form-data的node.js中间件,主要用于上传文件。
例如,要检索请求的(常规)字段:
let multer = require('multer');
let upload = multer();
app.post('form_submit', upload.fields([]), (req, res) => {
let formData = req.body;
console.log('form data', formData);
});