AngularJS 和 ExpressJS : how to read content sent by $http. put()

标签 angularjs node.js express

我对 angularJS 应用程序有问题,它向 nodejs 服务器发送回调。当我使用 POST 或 GET 方法时,一切正常,但是当我发送 PUT 请求时,出现错误。

如果我从 curl 调用服务器,它工作正常;当我使用 PUT 方法从 angularJS 调用一些远程服务器时,它也可以正常工作。所以问题出在我本地主机上angularJS和nodejs之间的合作,但我还没有弄清楚。

我的 Angular 方法,调用本地 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, status, headers, 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 应用程序中的错误消息。服务器从不按应有的方式打印 OK

{"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',
     url:'http://127.0.0.1:3000/s',
     params: {"test":true, _method: 'PUT'},
     headers :{'Content-Type':'application/json'}
        }).success(function(data, status, headers, config) {
            alert('OK');
        }).error(function(data, status, headers, config) {
            alert('error');
        }).catch(function(error){
            alert('catch' + JSON.stringify(error));
        });

关于AngularJS 和 ExpressJS : how to read content sent by $http. put(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135444/

相关文章:

css - 使用 SassDoc 为 sass 变量生成文档?

node.js - 如何通过 Node js中的 Sequelize 更新关联记录?

javascript - 防止 Angular 自定义指令模板中禁用的树节点上的单击事件

javascript - 如何在node js中同时对日期和各个日期的值数组进行排序?

json - 如何在 mongodb 更新调用中覆盖整个 json 文档

node.js - 如何在多台机器上集群 Node.js 应用程序

node.js - 循环遍历具有子数组的嵌入文档并将其显示在 EJS 文档上

angularjs - 无法访问 form.inputName.$dirty,其中 inputName 位于具有隔离范围的指令模板内

angularjs - 在 Ionic 中创建和显示 pdf

angularjs - 在 Neo4j 新版本中是否可以在没有插件的情况下压缩 REST API 响应 gzip?