简体   繁体   English

Node.js管道流与ajax和节点http模块

[英]Node.js piping streams with ajax and nodes http module

I have an express app with some ajax, calling some remote endpoints. 我有一个带有一些ajax的快速应用程序,调用一些远程端点。 At the moment, my api calls are posting to an endpoint on my local server. 目前,我的api调用正在发布到我本地服务器上的端点。 Express listens on these endpoints and pipes the request to the remote server and resolves the response. Express侦听这些端点并将请求传递给远程服务器并解析响应。

This is working for most of my endpoints, except for one POST method which requires a query parameter of code and a body of type Array[int] . 这适用于我的大多数端点,除了一个POST方法,它需要代码的查询参数和Array [int]类型的主体。 The response for each request to this endpoint returns 405. If I call the server endpoint directly within the ajax request, It returns successful. 每个请求对此端点的响应返回405.如果我直接在ajax请求中调用服务器端点,则返回成功。 Does this issue ring a bell for anyone? 这个问题对任何人都响了吗?

Here is what the data flow looks like. 这是数据流的样子。

$.ajax({
        type: "POST",
        url: "/promos/validate?code=testing",
        data: JSON.stringify([1]),
        success: function(data) {
           console.log(data)
        }.bind(this),
        error: function(xhr, status, err) {
           console.log(status)
        }.bind(this)
    });

And then we route with express 然后我们用快递路线

router.post('/promos/validate', function(req, res) {
  pipe(req, res).post(http://remoteUrl/promos/validate/code=testing);
});

In the post method, lives the http.request function which sends the following object as the options parameter 在post方法中,使用http.request函数,该函数将以下对象作为options参数发送

{ 
protocol: 'http:',
  query: '?code=testing',
  host: 'remote-api.com',
  port: 80,
  hostname: 'remote-api.com',
  href: 'http://remote-api.com?code=testing',
  path: '/promos/validate',
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'Content-Length': 8 } 
}

And finally we stream the request body to the server with write. 最后,我们使用write将请求主体流式传输到服务器。 Every time this happens, it returns 405. Any ideas? 每次发生这种情况,它都会返回405.任何想法?

Two things: the ajax request needed to set the content type to application/json and it turns out that the request was hitting 405 because the query was being separated into its own property when it should have been appended onto the 'path' property option. 两件事:将内容类型设置为application / json所需的ajax请求,结果是请求命中405,因为当应该将查询附加到'path'属性选项时,查询被分成了自己的属性。

I found this out by viewing the options list at Node.js docs - https://nodejs.org/api/http.html#http_http_request_options_callback 我通过查看Node.js文档中的选项列表找到了这一点 - https://nodejs.org/api/http.html#http_http_request_options_callback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM