简体   繁体   English

NodeJS 使用 POST 将 POST 传递给外部 API

[英]NodeJS passing POST to external API using POST

Getting a dreaded JSON error .得到一个可怕的 JSON 错误。

I am using an external API that allegedly takes a POST to add a user to a group.我正在使用一个据称采用 POST 将用户添加到组的外部 API。 in my nodeJS express app - I want to pass-thru the data coming from my app to the external API.在我的 nodeJS express 应用程序中 - 我想将来自我的应用程序的数据传递到外部 API。

my "GET" methods work - but now I am trying to take a form submitted to my app, and pass the data to an external API using "POST".我的“GET”方法有效 - 但现在我试图将表单提交给我的应用程序,并使用“POST”将数据传递给外部 API。

Here is the code I am testing (assume the api url and credentials are correct - and NOT the issue) I have tested the external API passing the same JSON object directly to the external API using Postman, and it works without error.这是我正在测试的代码(假设 api url 和凭据是正确的 - 而不是问题)我已经测试了使用 Postman 将相同的 JSON 对象直接传递给外部 API 的外部 API,并且它可以正常工作。

const express = require('express');
const router = express.Router();
const https = require('https');


    function callExternalAPI( RequestOptions ) {
        return new Promise((resolve, reject) => {
            https.request(
                RequestOptions,
                function(response) {
                    const { statusCode } = response;
                    if (statusCode >= 300) {
                        reject(
                            new Error( response.statusMessage )
                        );
                    }

                    const chunks = [];

                    response.on('data', (chunk) => {
                        chunks.push(chunk);
                    });

                    response.on('end', () => {
                        const result = Buffer.concat(chunks).toString();
                        resolve( JSON.parse(result) );
                    });

                }
            )
            .end();
        })
    }


    router.get('/thing', /*auth,*/ ( req, res, next ) => {

        callExternalAPI(
            {
                host: 'api_url',
                path: '/list',
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + new Buffer( auth_un + ':' + auth_pw ).toString('base64')
                }
            }
        )
        .then(
            response => {
                console.log(response);
            }
        )
        .catch(
            error => {
                console.log(error);             
            }
        );

    });


    router.post('/thing', /*auth,*/ ( req, res, next ) => {

        callExternalAPI(
            {
                host: 'api_url',
                path: '/addThing',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + new Buffer( auth_un + ':' + auth_pw ).toString('base64')
                },
                data: {
                    'group_id': req.body.group_id,
                    'person_id': req.body.person_id
                }
            }
        )
        .then(
            response => {
                console.log(response);
            }
        )
        .catch(
            error => {
                console.log(error);             
            }
        );

    });

module.exports = router;

console logging the req.body looks lie this控制台记录 req.body 看起来是这样的

{ group_id: '45b62b61-62fa-4684-a058-db3ef284f699',  person_id: '3b1c915c-3906-42cf-8084-f9a25179d6b2' }

And the error looks like this错误看起来像这样

undefined:1
<html><title>JSpring Application Exception</title>
<h2>JSpring Exception Stack Trace</h2>
<pre>SafeException: FiberServer.parsers.parseJSONBuf(): JSON parse failed.
^    
SyntaxError: Unexpected token < in JSON at position 0

Granted the console.log of the req.body does not have the required double quotes, but I think that is just the log dump format - but it might be munging the JSON.授予 req.body 的 console.log 没有所需的双引号,但我认为这只是日志转储格式 - 但它可能正在处理 JSON。 I have tried wrapping this in stringify;我曾尝试将其包装在 stringify 中; meaning something like this: data: JSON.stringify( req.body ) (but the same error occurs).意思是这样的: data: JSON.stringify( req.body ) (但发生同样的错误)。

callExternalAPI(
            {
                host: 'api_url',
                path: '/addThing',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic ' + new Buffer( auth_un + ':' + auth_pw ).toString('base64')
                },
                **data: JSON.stringify( req.body )**
            }
        )

I am testing this in postman, having the body be 'raw json' with headers as 'application/json' the body is this:我正在邮递员中对此进行测试,使正文为“原始 json”,标题为“应用程序/json”,正文是这样的:

{
    "group_id": "45b62b61-62fa-4684-a058-db3ef284f699", 
    "person_id": "3b1c915c-3906-42cf-8084-f9a25179d6b2"
}

You should try to write the POST payload in the request body instead of passing it inside the options object:您应该尝试在请求正文中写入POST 有效负载,而不是将其传递到选项对象中:

function callExternalAPI( RequestOptions ) {
  const { data, ...options } = RequestOptions;
  return new Promise((resolve, reject) => {
    const req = https.request(
      options,
      function(response) {
        const { statusCode } = response;
        if (statusCode >= 300) {
          reject(
            new Error( response.statusMessage )
          );
        }

        const chunks = [];

        response.on('data', (chunk) => {
          chunks.push(chunk);
        });

        response.on('end', () => {
          const result = Buffer.concat(chunks).toString();
          resolve( JSON.parse(result) );
        });

      }
    );
    req.write(JSON.stringify(data));
    req.end();
  })
}

In express you must use bodyParser At the top of the file when you initializing your express app add this lines在 express 中,您必须使用 bodyParser 在初始化 express 应用程序时在文件顶部添加此行

const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

https://medium.com/@adamzerner/how-bodyparser-works-247897a93b90 https://medium.com/@adamzerner/how-bodyparser-works-247897a93b90

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

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