Single-SPA localhost CROS origin Issue- React Application
Asked Answered
P

2

6

I'm new to react..I have react application which i migrated to Single-SPA. To integrate my application with the master application(platform which has many Vue single-spa applications) i have re-structured as

MainApp - It includes all the pages related to process - running under localhost:3000

root-html-file - it includes one index.html and package.json file index.html (running under localhost:5000- generate by SPA)

code: root-html-file -> index.html

<script type="systemjs-importmap">
      {
        "imports": {
    "myapp": "http://localhost:3000/",
    "single-spa": "https://cdnjs.cloudflare.com/ajax/libs/single-spa/4.3.7/system/single-spa.min.js",
    "react": "https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.development.js"
     }}</script>

Promise.all([System.import('single-spa'),System.import('react')]).then(function (modules) {
          var singleSpa = modules[0];
            singleSpa.registerApplication(
                'myapp',
                () => System.import('myapp'),
                location => true
            );
          singleSpa.start();

myapp application working fine as standalone. Only when running root-html-file application (npm run serve) which will load myapp application into it causes CROS origin issue.Please find the screenshot

enter image description here

Please guide me if i'm wrong direction.

Philomenaphiloo answered 21/5, 2020 at 10:24 Comment(0)
O
2

You need to add the Access Control Allow Origin headers to the React App. In webpack, it can be done by adding the below to the webpack.config.js file

devServer: {
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
    "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
  }
}
Orbicular answered 28/6, 2020 at 0:16 Comment(1)
This is not working for me? Did it work for you?Organogenesis
N
0

In case the other answers are not working, or in case if you don't have the webpack config and are using Vite, Craco or anything else instead, then you can try this.

The concept is, let's say you have

Root project -> running at localhost:5000

Child Project -> You have built it and then hosted the built files -> which is running at localhost:3000

You will get CORS in the root project if you try to access resources from an endpoint(5000) from any other endpoint(3000).

You can try hosting the child app build folder using the below command in the command prompt with --cors flag.

npx http-party/http-server --port=3000 --cors

Here the --cors flag will make it suitable to be consumed by localhost:5000 (i.e. your root project).

Neat answered 25/1 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.