標籤:
這也是最近遇到的坑,還是之前那個項目,現在要實現登入功能。
背景:註冊功能之前已經跑通了。前端用的是jquery後台是springMVC。鑒於註冊和登入有些介面功能是類似的(比如註冊確保郵箱是沒有註冊過,而登入是確保註冊過),於是後台還準備用註冊的那套介面。
登入的介面get請求是沒問題的,但是post卻出了問題:後台收不到請求體裡的內容。
後來發現是jquery和angular的post行為有些區別,於是我做了個實驗。
<!DOCTYPE html><html lang="en" ng-app="app"><head> <meta charset="UTF-8"> <title>Title</title></head><body ng-controller="body"><button id="ng-btn" ng-click="sendNgPost()">ng-btn</button><button id="jq-btn">jq-btn</button><button id="js-btn">js-btn</button></body><script src="bower_components/jquery/dist/jquery.js"></script><script src="bower_components/angular/angular.js"></script><script>angular.module(‘app‘,[]).controller(‘body‘,function ($scope,$http) { var data={username:‘zhangdongming‘,password:‘123123123‘}; $scope.sendNgPost=function () { $http({ method:‘POST‘, url:‘/fromNg‘, data:data }).then(function (res) { console.log(res); }) }; $(‘#jq-btn‘).click(function () { $.post(‘/fromJq‘,data,function (data) { console.log(data); }) }); function post(sendData) { var xhr=new XMLHttpRequest(); xhr.open(‘post‘,‘/fromJs‘,true); xhr.onload=function () { console.log(xhr.responseText); }; xhr.send(data); } var btn=document.querySelector(‘#js-btn‘); btn.onclick=function () { post(data); }});</script></html>
這段代碼的作用就是用angularjs,jquery和js發post請求
服務端是express寫的
var express=require("express");var mime = require(‘mime‘);var http = require(‘http‘);var util = require(‘util‘);var url = require(‘url‘);var fs = require(‘fs‘);var path=require(‘path‘);var formidable=require(‘formidable‘);var querystring = require(‘querystring‘);var bodyParser=require("body-parser");app=express();// var data=[// {screenName:"zhangdongming",phoneNumber:"15210938964",email:"[email protected]"}// ];app.use(express.static(path.join(__dirname)));app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended:false}));app.get(‘/‘,function (req,res) { res.sendfile(path.resolve("client.html"));});app.post(‘/fromNg‘,function (req,res) { console.log(req.body); res.send(‘false‘);});app.post(‘/fromJq‘,function (req,res) { console.log(req.body); res.send(‘false‘);});app.post(‘/fromJs‘,function (req,res) { console.log(req.body); res.send(‘false‘);});app.listen(3000);
注意,body-parser中介軟體use我寫了兩句。
好了現在看看這三個請求是什麼樣子的。
這個是angular的
用jquery
用js
注意看Content-Type ng是appliction/json,jq是application/x-www-form-urlencoded,js是text/plain。
而Request Payload中,ng是json字串,jq經過了序列化,js是個???
對於express的body-parse中介軟體來說,兩種格式的都可以,只需要寫好對應的use就可以了。
而我們背景介面寫法只能接收urlencoded格式的,json是收不到的。
這種事情自然是前端想辦法,很簡單,都轉成jquery的格式就行了。
具體來講,對於js來講,加上兩句:
1.換格式config(function ($httpProvider) {
$httpProvider.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded;charset=utf-8‘;
})
2.序列化工作就比較簡單了,因為用angular一般會預設帶上jqeruy,$.param()可以方便的完成這項工作
$http({
method: ‘POST‘,
url: ‘/fromNg‘,
data: $.param(data)
}).then(function (res) {
console.log(res);
})
以上。
angular js jquery中post請求的一點小區別