我对 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/