0

I have a serverless express app. In the app I have a app.get called '/', which should call an api, retrieve the data from the api and send it back to the user.

https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev

I can see data as json on the page being returned.

This is my index.js of the lambda function:

const serverless = require('serverless-http');
const express = require('express');
const request = require('request');
const app = express()

app.get('/', function (req, res) {

  var options = { method: 'POST',
   url: 'https://some.api.domain/getTopNstc',
   headers:
    {   'Content-Type': 'application/json' },
   body: {},
   json: true
  };

  request(options, function (error, response, body) {
    console.log('request call')
   if (error) throw new Error(error);
  // res.status(200).send(response);
  res.json(response);
  });
});

module.exports.handler = serverless(app);

However I would to be able to call the lambda '/' via axios (or other promise-request library)

I've tried to use the following code to make a call to my lambda:

axios.get('https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev', {
  headers: {
    'Content-Type': 'application/json',
   },
  body:{}
  }).then((res) => {
  console.log(res);
 });

Failed to load https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'myDomain' is therefore not allowed access. bundle.js:31 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://y31q4zn654.execute-api.eu-west-1.amazonaws.com/dev with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Api gateway config: enter image description here

2

1 Answer 1

1

I concur with @KMo. Pretty sure this is a CORS issue. There is a module in npm exactly for this purpose, read up about it here.

To install it, run npm install -s cors

Then in your express app, add the following:

const express = require('express'); const app = express(); const cors = require('cors'); app.use(cors());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.