Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

node.js - AngularJS + ExpressJS. Proxy POST request is pending

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);
});

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

Here is how I post:

$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");});

What's wrong?

EDIT: Here is the request as seen on the console: enter image description here

What should I check to give more information?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should have mentioned you were using the request library:

https://github.com/mikeal/request

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

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

or as a chained call:

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

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.

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

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.

Edit: 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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...