1

When I call my API via my web browser I get the following result:

{"statusCode": 200, "body": "\"Cheers from AWS Lambda!\""}

However, I am now struggeling to show body via axios. Do you see what I am doing wrong?

import axios from "axios";
import React, { Component } from "react";

class App extends Component {
  state = {
    messages: []
  };

  componentDidMount() {
    axios
      .get(
        "https://12345.execute-api.eu-central-1.amazonaws.com/prod/get-data"
      )
      .then(response => {
        const messages = response.data;
        this.setState({ messages });
      });
  }

  render() {
    return (
      <ul>
        {this.messages}
        Test
        {this.state.messages.map(message => (
          <li>{message}</li>
        ))}
      </ul>
    );
  }
}
export default App;
Joey Coder
  • 3,199
  • 8
  • 28
  • 60
  • what is `this.messages` ? where is `messages ` function ..is it `{JSON.stringify(this.state.messages)}` ? – blueseal Nov 24 '19 at 09:30
  • That just shows me `[]`. It seems that messages doesn't receive the data it should receive? – Joey Coder Nov 24 '19 at 09:31
  • Can you console.log(response.data) ? What is there? – SuleymanSah Nov 24 '19 at 09:32
  • Now that I looked in the console it actually says `Access to XMLHttpRequest at 'https://12345.execute-api.eu-central-1.amazonaws.com/prod/get-data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` I guess that's not a react problem, but a permission problem? What confuses me is that I can call it via my web browser without any problems. – Joey Coder Nov 24 '19 at 09:35
  • it may help you https://stackoverflow.com/a/18643011/5124488 – blueseal Nov 24 '19 at 09:37
  • Is it possible to share the real endpoint? – SuleymanSah Nov 24 '19 at 09:42
  • Apart from the CORS error, if you want to display the message body you will need to do `
  • {this.state.messages.body}
  • ` If the endpoint returns a single object, there is no need to use map(). because in your `setState()` you have replaced the initial state which was an empty array with the object. – Afia Nov 24 '19 at 09:57
  • hi, try this plugin for chrome browsers: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en – Ehsan Sadeghi Nov 24 '19 at 10:14