Tom3652
Tom3652

Reputation: 2967

How to make an http request from Atlas Trigger in NodeJS?

I have a basic MongoDB Atlas trigger in NodeJS :

exports = function(changeEvent) {
  
 // Make an http request
  
};

My goal is to call an AWS lambda function from this trigger, so i would like to know the syntax to make a basic GET request to a specific endpoint from the NodeJS code.

EDIT :

I am unable to run axios, the dependency is indeed installed but the get method doesn't seem to exist.

enter image description here

Upvotes: 1

Views: 1010

Answers (2)

Alex Blex
Alex Blex

Reputation: 37048

First of all, for Lambda functions you will be better off with Event Bridge which is designed exactly for this purpose and utilizes native AWS services directly.

Secondly, you cannot trigger lambda directly without exposing aws console credentials. The better option is to set up an API gateway which accepts http requests and triggers the lambda.

Finally, assuming the API gateway is already there, the Atlas trigger would be as simple as:

exports = async function(changeEvent) {
  const requests=require("requests");
  return await requests("<API gateway url>", {method: "POST", data:{changeEvent}});
};

UPDATE

Syntax for axios version:

exports = async function(changeEvent) {
  const axios = require('axios');  
  return axios.default.post('<API gateway url>',changeEvent);
};

Upvotes: 1

Aniket Raj
Aniket Raj

Reputation: 2141

NPM to install axios in your node js app -> npm i axios

i have put data key in axios to send some data to another server if needed:

const axios = require("axios");

async function Api() {
  const response = await axios.get("url",{
  headers : {
    "Content-Type" : "application/json"
  },
  data : {name : "someName"}
  })
  
  //receive data from request
  console.log(response.data);
  return response.data;
}


Api()

Upvotes: 2

Related Questions