AngularJS和ExpressJS:如何读取$http.put()发送的内容

前端之家收集整理的这篇文章主要介绍了AngularJS和ExpressJS:如何读取$http.put()发送的内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有angularJS应用程序的问题,它将回调发送到nodejs服务器.当我使用POST或GET方法时,一切正常,但是当我发送PUT请求时,我收到错误.

如果我从curl调用服务器,它工作正常;当我使用PUT方法从angularJS调用一些远程服务器时,它也可以正常工作.所以问题在于我的localhost上的angularJS和nodejs之间的合作,但我还没有弄明白.

我的角度方法,调用本地nodejs服务器:

$http({
   method  :'PUT',url:'http://127.0.0.1:3000/s',data: $.param({"test":true,_method: 'PUT'}),headers :{'Content-Type':'application/x-www-form-urlencoded'}
        }).success(function(data,status,headers,config) {
            alert('OK');
        }).error(function(data,config) {
            alert('error');
        }).catch(function(error){
            alert('catch' + JSON.stringify(error));
        });

我的nodejs文件

var express        =    require("express");
var MysqL          =    require('MysqL');
var bodyParser     =    require('body-parser')
var methodOverride =    require('method-override');
var app            =    express();

//use body parser to get json
app.use(bodyParser.json())
// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// allow PUT from browser
app.use(methodOverride('_method'));

app.put('/s',function(req,res){
  console.log('OK');
  //handle_database_put(req,res);
  res.set('Access-Control-Allow-Origin','*');
  res.set('Access-Control-Allow-Methods','PUT,GET,POST,DELETE,OPTIONS');
  res.send('PUT OK');
});

app.listen(3000);

编辑这是Angular应用程序中的错误消息.服务器永远不会打印正常

{"data":null,"status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"url":"http://127.0.0.1:3000/s","data":"test=true&_method=PUT","headers":{"Content-Type":"application/x-www-form-urlencoded","Accept":"application/json,text/plain,*/*"}},"statusText":""}

编辑2:我刚刚注意到,请求不被识别为PUT,而是被视为OPTIONS

解决方法

试试这个

$http({
   method  :'PUT',params: {"test":true,_method: 'PUT'},headers :{'Content-Type':'application/json'}
        }).success(function(data,config) {
            alert('error');
        }).catch(function(error){
            alert('catch' + JSON.stringify(error));
        });

猜你在找的Angularjs相关文章