AngularJS + ExpressJS.代理 POST 请求待处理 [英] AngularJS + ExpressJS. Proxy POST request is pending

查看:49
本文介绍了AngularJS + ExpressJS.代理 POST 请求待处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 AngularJS + Express我有以下代码将我的请求代理到远程服务:

Using AngularJS + Express I have the following code to proxy my requests to a remote service:

app.get('/api.json', function (req, res) {
    req.pipe(request("http://test-api.com/api.json")).pipe(res);
});

app.post('/api.json', function (req, res) {
    req.pipe(request.post("http://test-api.com/api.json")).pipe(res);
});

所有 GET 请求都可以正常工作,但是 POST 请求在我的浏览器中处于待处理状态.

All GET requests works fine, however the POST requests are pending in my browser.

这是我发帖的方式:

$http({
   method: 'POST',
   url: '/api.json',
   data: $.param({
       "title": not.title,
       "desc": not.description
  }),  // pass in data as strings
   headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function () {alert("Success");});

怎么了?

这是在控制台上看到的请求:

Here is the request as seen on the console:

我应该检查什么才能提供更多信息?

What should I check to give more information?

推荐答案

你应该提到你在使用请求库:

You should have mentioned you were using the request library:

https://github.com/mikeal/request

request.post() 期望表单作为第二个参数:

request.post() is expecting the form either as the second parameter:

request.post('http://service.com/upload', {form:{key:'value'}})

或作为链式调用:

request.post('http://service.com/upload').form({key:'value'})

因为您没有将它作为参数传递,所以 request.form() 根本没有发出任何请求,等待您调用 .form().但是由于您也没有这样做,不会发生任何请求,因此不会返回任何答案,因此您的应用程序会看到请求失败而没有响应.您可以在 chrome 开发者工具网络选项卡中看到,请求将在其中显示(失败)"状态代码.

Because you're not passing it as an argument, request.form() is not making any request at all, waiting for you to call .form(). But since you're not doing that either, no request ever happens, so no answer is ever returned, and thus your application sees that the request failed without response. You can see that in the chrome developer tools network tab, where the request will show a "(failed)" status code.

所以只需从当前请求中获取表单数据并将其传递给 request.form 就可以了.

So just obtain the form data from the current request and pass it to request.form and it should work.

为了将来参考,调试器会立即告诉您错误是什么.我推荐 Webstorm 中包含的那个,但可以随意使用任何调试器.

For future reference, a debugger would have told you what the mistake was instantly. I recommend the one included with Webstorm, but feel free to use any debugger at all.

还没有尝试过,但这是我会尝试的

Haven't tried but this is what I would try

app.post('/api.json', function (req, res) {
    req.pipe(request.post("http://test-api.com/api.json", {form:req.body})).pipe(res);
});

这篇关于AngularJS + ExpressJS.代理 POST 请求待处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆