skip to Main Content

I have built a test project that has a simple api where the front end interacts with the backend and receives a string back. I built this project to test how I would host this on aws ec2 instances. What I have done so far is, built images for the frontend and the backend and then pulled them in the respective ec2 instances and the end point urls have been set to the instance public DNS. Now, I seem to be getting a CORS issue that I am not sure about. I do have a cors mapping bean in the backend which was working fine locally but it is no longer working when hosted on aws. The code for the frontend and the backend is given below:

import './App.css';
import { useState } from 'react';

function App() {

const [message, setMessage]=useState("");
  async function handleClick() {

    const baseUrl = 'http://ec2-xx-xx-xxx-xx.eu-xxxx-x.compute.amazonaws.com'
    //process.env.REACT_APP_BASE_URL || 'http://localhost:8080';;


    fetch(baseUrl+"/test", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      mode: 'cors',
      credentials: 'include',
    })
      .then((response) => {
    

        return response.json();
      })
      .then((data) => {
        console.log(data.message)
        setMessage(data.message)
        
      })
      .catch((err) => console.log(err));
     


  }
  return (
    <div className="App">
      <button onClick={()=> handleClick()}>
        CLICK ME
      </button>
      <div>
      <p>{message}</p>
      </div>
      
    </div>
  );
}

export default App;


package com.example.test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
@EnableWebMvc // Enable WebMvc support
public class TestApplication {


    

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/test").allowedOrigins("http://ec2-xx-xx-xx-xx.eu-xxxx-x.compute.amazonaws.com");
            }
        };
    }


}

package com.example.test;



import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/test")
public class TestController {

    @GetMapping(produces = "application/json")
    private Response getTest() {
Response response= new Response("Hello");
        return response;
    }
}

Here is the error i get

enter image description here

3

Answers


  1. Hassan,

    CORS is a backend configuration.

    I cannot give a direct answer since I am not familiar with your backend.

    I can see that you are using the fetch API in the frotend. With an express.js backend I would simply use the CORS plugin and I am fine.

    Could you give a screenshot of your CORS error in dev console? Also if you are fine testing against my backend I could provide you some CORS enabled backend to test your frotend.

    Login or Signup to reply.
  2. This is my code with express.

    It has been observed to work with any origin. But it has parts you don’t need. You can take the relevant ones and learn.

    const express = require('express')
    const fs = require('fs');
    const https = require('https');
    const multer = require('multer');
    const morgan = require('morgan-body');
    const cors = require('cors');
    const tus = require('tus');
    const bodyParser = require('body-parser');
    const basicAuth = require('express-basic-auth');
    
    const cert = fs.readFileSync(__dirname + "/localhost.pem", 'utf-8');
    const key = fs.readFileSync(__dirname + "/localhost-key.pem", 'utf-8');
    const app = express();
    morgan(app);
    app.use(cors());
    app.use(express.json());
    app.use(express.static(__dirname + "/public"));
    
    app.use(bodyParser.json()); 
    app.use(bodyParser.urlencoded({ 
        extended: true
    }));
    
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'uploads')
        },
        filename: function (req, file, cb) {
            cb(null, file.originalname)
        }
    })
    var upload = multer({ storage: storage })
    
    app.post('/uploadmultiple', upload.array('uploadFiles', 12), (req, res, next) => {
        const files = req.files
        if (!files) {
            const error = new Error('Please choose files')
            error.httpStatusCode = 400
            return next(error)
        }
        res.send(files)
    })
    
    https.createServer({key: key, cert: cert}, app).listen(2324, () => {
        console.log('Server is up on port 2324');
    })
    

    I can see that you are having an issue with AWS. Is there a different way to solve the problem?

    Why give backend Java code when you are using AWS? Why are you using two different endpoints when you could be using relative URL?

    CORS errors exist for a reason (security). Perhaps you could use the same origin and solve it?

    Login or Signup to reply.
  3. use @CrossOrigin annotation in the main class of the web application

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search