1

过去几天我一直在尝试解决这个问题,但没有运气,我对 Node Js 和 Lambda 还很陌生。我正在尝试使用 lambda 创建一个 API,当我调用这个新 API 时,我想在 Shopify 中创建一个新的重定向对象。我的函数中运行了以下代码

const http = require('https')

exports.handler = async (event) => {
    return httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
    });
};
function httprequest() {
     var username = "shopify-api-private-username";
     var password = "shopify-api-private-password";
     var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
    
     return new Promise((resolve, reject) => {
        const options = {
            host: 'store-name.myshopify.com',
            path: '/admin/api/2020-04/redirects.json',
            port: 443,
            method: 'POST',
            headers: {
              'Authorization': auth,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({"redirect":{"path":"http://www.apple.com/forum","target":"http://forums.apple.com"}})
        };
        
        const req = http.request(options, (res) => {
            console.log(res);
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}

尽管我不断更改代码,但我不断收到以下错误。在响应中添加控制台日志后,我看到以下内容,不确定这是 Lambda/Node 响应还是 Shopify:

在此处输入图像描述

Function logs:
  servername: 'store-name.myshopify.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 11,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'store-name.myshopify.com',
      _readableState: [ReadableState],
      readable: true,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: [HTTPParser],
      _httpMessage: [Circular],
      [Symbol(res)]: [TLSWrap],
      [Symbol(asyncId)]: 4,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /admin/api/2020-04/redirects.json HTTP/1.1\r\n' +
      'Authorization: Basic base64code_replace_for_security_reasons=\r\n' +
      'Content-Type: application/json\r\n' +
      'Host: store-name.myshopify.com\r\n' +
      'Connection: close\r\n' +
      'Content-Length: 0\r\n' +
      '\r\n',
    _onPendingData: [Function: noopPendingOutput],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object],
      requests: {},
      sockets: [Object],
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    insecureHTTPParser: undefined,
    path: '/admin/api/2020-04/redirects.json',
    _ended: false,
    res: [Circular],
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: HTTPParser {
      '0': [Function: parserOnHeaders],
      '1': [Function: parserOnHeadersComplete],
      '2': [Function: parserOnBody],
      '3': [Function: parserOnMessageComplete],
      '4': null,
      _headers: [],
      _url: '',
      socket: [TLSSocket],
      incoming: [Circular],
      outgoing: [Circular],
      maxHeaderPairs: 2000,
      _consumed: false,
      onIncoming: [Function: parserOnIncomingClient]
    },
    maxHeadersCount: null,
    reusedSocket: false,
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      authorization: [Array],
      'content-type': [Array],
      host: [Array]
    }
  },
  [Symbol(kCapture)]: false

任何帮助,将不胜感激。先感谢您。

顺便说一句,我直接在一个新的 Lambda 函数上执行此操作。我唯一的文件是 index.js。

节点版本 Node.js 12.x

4

1 回答 1

1

正如评论中正确指出的那样,您的代码无法正常工作的简短解释是因为错误请求。这是一个错误的请求,因为您实际上并没有随请求一起发送有效负载。您从 Stack Overflow 获得的代码可能是用于 GET 请求的,而简单地将body属性添加到选项对象将不起作用。因为根据HTTPS 的 Node.js 文档选项对象没有任何名为body的属性。

根据HTTP 请求的 Node.js 文档,您需要使用write函数发送 POST 数据。

// Write data to request body
req.write(postData);

要修复您的代码,请添加内容长度属性并写入帖子数据。检查代码注释。

    const http = require('https')
    
    exports.handler = async (event) => {
        return httprequest().then((data) => {
            const response = {
                statusCode: 200,
                body: JSON.stringify(data),
            };
        return response;
        });
    };
    function httprequest() {
         var username = "shopify-api-private-username";
         var password = "shopify-api-private-password";
         var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
        
         return new Promise((resolve, reject) => {
            const data = JSON.stringify({"redirect":{"path":"http://www.apple.com/forum","target":"http://forums.apple.com"}});
            const options = {
                host: 'store-name.myshopify.com',
                path: '/admin/api/2020-04/redirects.json',
                port: 443,
                method: 'POST',
                headers: {
                  'Authorization': auth,
                  'Content-Type': 'application/json',
                  'Content-Length': data.length // Added content length
                }
            };
            
            const req = http.request(options, (res) => {
            console.log(res);
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
        // write POST data
        req.write(data)
       req.end();
    });
}

我已经验证了这段代码,它在本地和 AWS Lambda 函数中都能正常工作。如果您现在收到 422,则表示已添加重定向。

除此之外,考虑使用提供更好的错误处理、速率限制和其他必需功能的Shopify API Node.js。您还可以查看Shopify 的官方节点库

于 2020-06-30T13:28:06.247 回答