简体   繁体   中英

How do I serve a React application from an Spring Boot application?

I would like to serve the results of the Webpack build of a ReactJS UI application from a Spring Boot server application.

As the Webpack build generates all the assets in a "dist" folder ie index.html, bundle.js, etc... Accessed as ie http://localhost/index.html

And the Spring Boot application serves the API URLs from ie http://localhost/api/xxx

  1. create .env file in the root of react project (next to package.json)
  2. put PUBLIC_URL=/nameContextRoot in .env file (name of context root typically is name of war file)
  3. build react project npm run build

For me it generates its contents in build directory of react project

  1. copy the contents of the build directory to the spring-boot apps static directory

static directory should be a normal folder in src/main/resources

  1. clean and rebuild spring boot project and run it

  2. Contents are now properly served

UPDATE

Spring Boot structure

D:.
├───.mvn
│   └───wrapper
├───.settings
├───src
│   ├───main
│   │   ├───java
│   │   │   └───my.java.stuff
│   │   ├───resources
│   │   │   └───static
│   │   │       └───static
│   │   │           ├───css
│   │   │           └───js
│   │   └───webapp
│   └───test
│       └───java
│           └───my.java.tests
├───target
│   ├───classes
│   │   ├───java.classes
│   │   └───static
│   │       ├───css
│   │       ├───js
│   │       └───static
│   │           ├───css
│   │           └───js
│   ├───generated-sources
│   │   └───annotations
│   ├───m2e-wtp
│   │   └───web-resources
│   │       └───META-INF
│   │           └───maven
│   │               └───java.stuff
│   ├───maven-archiver
│   ├───maven-status
│   │   └───maven-compiler-plugin
│   │       └───compile
│   │           └───default-compile
│   ├───rclient-0.0.1-SNAPSHOT
│   │   ├───META-INF
│   │   └───WEB-INF
│   │       ├───classes
│   │       │   ├───java stuff
│   │       │   └───static
│   │       └───lib
│   └───test-classes
└───WebContent
    └───META-INF

ReactJS project structure

D:.
├───build
│   └───static
│       ├───css
│       └───js
├───node_modules
├───public
└───src
    ├───components
    ├───domain
    └───util

Your api endpoints will be also served below the context root. They have nothing to do with React.

The hint of @Codo to use a reverse proxy to access the static content is still valid. But here you asked specifically for how to host the react app in a spring boot application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM