学前端,找工作,点这里

后台代码



var express = require('express');

// var bodyParse = require("body-parser");

var multipart = require('connect-multiparty');

var app = express();

var multipartMiddleware = multipart();

// app.use(bodyParse.urlencoded({extended:true}));

//设置跨域访问

app.all('*', function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Headers", "X-Requested-With");

res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

res.header("X-Powered-By", ' 3.2.1');

// res.header("Content-Type", "application/json;charset=utf-8");

next();

});

app.get('/api', function(req, res) {

res.status(200);

res.json({result: 'success'});

});



app.post('/post',multipartMiddleware,function(req,res){

res.json({result: 'success', data: req.body});

});

//配置服务端口

var server = app.listen(3000, function() {

var host = server.address().address;

var port = server.address().port;

console.log('Example app listening at http://%s:%s', host, port);

});
 

前台代码:



<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

</head>

<body>

<form id="J_form">

<p>用户名:<input type="text" name="username"></p>

<p>密码:<input type="password" name="password"></p>

<p><input type="button" value="提交" id="J_submit"></p>

</form>

<script>

var btn = document.querySelector("#J_submit");

btn.onclick = function(){

var xhrs = new XMLHttpRequest();

xhrs.open("post","http://localhost:3000/post",false);

//POST方式需要自己设置http的请求头

// xhrs.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

var data = new FormData();

data.append("username",document.querySelector("input[name='username']").value);

data.append("password",document.querySelector("input[name='password']").value);

xhrs.send(data);

};

</script>

</body>

</html>
 
 

connect-multiparty:nodejs后台文件上传模块儿

1.安装模块:

npm install connect-multiparty --save
 

2.引入模块


var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();

3.使用模块



app.post('/formdata',multipartMiddleware, function (req,res) {

res.send(req.body,req.files,req.files.file.path);//分别返回body,文件属性,以及文件存放地址
 

4.设置上传路径

app.use(multiparty({uploadDir:'/upload' }));//设置上传文件存放的地址
 
注意:文件上传前端form标签里做这样的标识enctype="multipart/form-data"
 
学完还想练练?点这里