Javascript 非常简单的 AngularJS $http POST 结果为“400(错误请求)”和“无效的 HTTP 状态代码 400”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26141359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Very Simple AngularJS $http POST Results in '400 (Bad Request)' and 'Invalid HTTP status code 400'
提问by EarlD
I have a very simple .NET Web API hosted in Azure, with two very simple methods:
我在 Azure 中托管了一个非常简单的 .NET Web API,有两个非常简单的方法:
[EnableCors(origins: "http://simpleapiearl.azurewebsites.net", headers: "*", methods: "*")]
public class EnvelopesController : ApiController {
// GET: api/Envelopes
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
// POST: api/Envelopes
public string Post([FromBody]Envelope env) {
return "rval: " + env + " (and my addition to env)";
}
}
I have created a simple plunkto call these methods. In my AngularJS code, I'm making two very simple $http calls. The GET works fine. The POST, however, always returns a "400 (Bad Request)", followed shortly in my WebStorm console by "XMLHttpRequestion cannot load ... Invalid HTTP status code 400".
我创建了一个简单的 plunk来调用这些方法。在我的 AngularJS 代码中,我进行了两个非常简单的 $http 调用。GET 工作正常。但是,POST 总是返回“400(错误请求)”,然后在我的 WebStorm 控制台中很快返回“XMLHttpRequestion 无法加载...无效的 HTTP 状态代码 400”。
Any and all suggestions appreciated!
任何和所有建议表示赞赏!
EDIT!!
编辑!!
Hello, and thanks for the very fast responses. I just realized I forgot to add some very relevant detail.
您好,感谢您的快速回复。我刚刚意识到我忘记添加一些非常相关的细节。
The parameter to my POST method is what I call an Envelope object, which contains two properties: listingId (int), and Description (string). When I add the urlencoded Content-Type header, and pass '{"listingId":1234, "Description":"some description"}'as my POST data, the env parameter in my POST method on the server is NULL (that is, it seems unable to parse the JSON I'm providing). Sorry this was omitted from original post.
我的 POST 方法的参数就是我所说的 Envelope 对象,它包含两个属性:listingId (int)、 和Description (string)。当我添加 urlencoded Content-Type 标头,并'{"listingId":1234, "Description":"some description"}'作为我的 POST 数据传递时,服务器上我的 POST 方法中的 env 参数为 NULL(也就是说,它似乎无法解析我提供的 JSON)。抱歉,这在原始帖子中被省略了。
回答by allenhwkim
I think this post would be helpful.
我认为这篇文章会有所帮助。
How do I POST urlencoded form data with $http in AngularJS?
如何在 AngularJS 中使用 $http POST urlencoded 表单数据?
By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".
默认情况下,$http 服务将通过将数据序列化为 JSON,然后使用内容类型“application/json”发布它来转换传出请求。当我们想将值作为 FORM 帖子发布时,我们需要更改序列化算法并使用内容类型“application/x-www-form-urlencoded”发布数据。
This is the modified plnkr from yours. Your code is missing conversion of JSON to encoded url.
这是您修改后的 plnkr。您的代码缺少 JSON 到编码 url 的转换。
http://plnkr.co/edit/4aeEDz73qgHSfOv1sBgn?p=preview
http://plnkr.co/edit/4aeEDz73qgHSfOv1sBgn?p=preview
$http({
method: 'POST',
url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
data: env,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).
回答by EarlD
I found a blog post that corrected my issue:
我找到了一篇博客文章,纠正了我的问题:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
Thanks to everyone for helping me out!
感谢大家帮助我!
回答by quirimmo
With AngularJS you can do in an easier way.
使用 AngularJS,您可以更轻松地完成任务。
You can inject $httpParamSerializerand then prepare your data through $httpParamSerializer(data).
您可以注入$httpParamSerializer,然后通过$httpParamSerializer(data).
So your call should look something like:
所以你的电话应该是这样的:
$http({
method: 'POST',
url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
data: $httpParamSerializer(env),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

