简体   繁体   中英

Displaying an image on API endpoint using aws lambda and node.js

Right now I am editing the code inline on AWS lambda. This is what I have currently:

var qrImage = require('qr-image');


exports.handler = async (event) => {
    return sendRes(200,'hi');
};
/*
const sendRes = (status, body) => {
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "text/html"
    },
    body: body
  };
  return response;
}; 
*/

const sendRes = (status, body) => {
  const svg_string = qrImage.imageSync('http://www.nodejs.org',{ type: 'png', size: 20 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/jpeg"
    },
    body: svg_string
  };
  return response;
};

This outputs the text Internal server error.

The code below creates a png file and stores it. The functionality I would like on lambda is to simply display the image(No saving involved) when I access the endpoint. But I am not sure how to go about it (New to Lamda, Node.js). What exactly should I be looking into?

var qrImage = require('qr-image');
var fs = require('fs');

qrImage
    .image("http://www.nodejs.org", {type:'png', size:20})
    .pipe(fs.createWriteStream("MyQRCode.png"));

EDIT I made some small changes and this appears to be working

var qrImage = require('qr-image');

exports.handler = async (event) => {
    return sendRes(200,'hi');
};

const sendRes = (status, body) => {
  const svg_string = qrImage.imageSync('this is AWS!', { type: 'svg', size: 10 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/svg+xml"
    },
    body: svg_string
  };
  return response;
};

If you are only returning the image with the help of lambda then sync will also work, here the code for it

const sendRes = (status, body) => {
  const svg_string = qr.imageSync('http://www.nodejs.org', { type: 'png', size: 20 });
  var response = {
    statusCode: status,
    headers: {
      "Content-Type": "image/jpeg"
    },
    body: svg_string
  };

  return response;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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