javascript – Why is the fetch request to AWS Express server failing?

Question

I have upload an express app to an AWS Elastikbeanstalk instance. When I enter the production url into chrome it returns a JSON with the data I want. Here is that code:

const express = require("express");
const axios = require('axios');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 5000;

app.use(cors());

app.listen(port, () => {
    console.log("listening on " + port);
})

app.get("https://wordpress.stackexchange.com/", (req, res) => {
    let login = process.env.USER
    let pass = process.env.PASS
    
    axios({
        method: 'get',
        url: process.env.URL,
        auth: {
            username: login,
            password: pass
        }
    }).then(function (response) {
        res.send(response.data);
        
      })
      .catch(function (error) {
        console.log(error);
        return;
      });
    
    
})

So just one express route that gets a JSON from an API using axios. Again when I enter the production URL into chrome or test this locally it works.

Then I make a fetch request from my wordpress front end to the production URL all I get is

TypeError: Failed to fetch

after a few second delay. Here is that fetch request:

//Load cards onlick with API
function wpb_hook_javascript() {
    ?>
        <script>
         function loadCards(){
             console.log("click");
             
                    
             fetch('<The-URL-of-AWS-SERVER', {
                 method: 'GET'
             })
                .then(response => console.log(response))
                //.then(data => console.log(data))
                .catch((error) => {
                    console.error('Error:', error);
                });
         }
        </script>
    <?php
}
add_action('wp_head', 'wpb_hook_javascript');

What am I doing wrong?

0
TDonnally 2 weeks 2021-07-15T16:06:38-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse