AngularJS和ExpressJS:如何读取$http.put()发送的内容
发布时间:2020-12-17 17:15:00 所属栏目:安全 来源:网络整理
导读:我有angularJS应用程序的问题,它将回调发送到nodejs服务器.当我使用POST或GET方法时,一切正常,但是当我发送PUT请求时,我收到错误. 如果我从curl调用服务器,它工作正常;当我使用PUT方法从angularJS调用一些远程服务器时,它也可以正常工作.所以问题在于我的loc
我有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)); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |