angular2 post以“application/x-www-form-urlencoded”形式传参的解决办法

angular2 post以“application/x-www-form-urlencoded”形式传参的解决办法

http://blog.csdn.net/tianjun2012/article/details/51427417

https://www.cnblogs.com/zhangdongming/p/5856402.html

代码如下: authenticate(data) { var username = data.credentials.username; var password = data.credentials.password; var creds = "username=" + username + "&password=" + password; var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); this.http.post('http://localhost:3001/sessions/create', creds, { headers: headers }) .map(res => res.json()) .subscribe( data => this.saveJwt(data.id_token), err => this.logError(err), () => console.log('Authentication Complete') ); }

angular js jquery中post请求的一点小区别

 

     这也是最近遇到的坑,还是之前那个项目,现在要实现登录功能。

     背景:注册功能之前已经跑通了。前端用的是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:"fortunewheel@sina.com"}
// ];
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);
})


以上。
 
 
原文地址:https://www.cnblogs.com/annie211/p/7883385.html