【发布时间】:2021-04-07 08:49:24
【问题描述】:
我的前端和后端应用程序有问题。我有一个为前端运行的 React.js 应用程序和一个运行 React 应用程序正在调用的 Java Spring Boot 应用程序。当它们都在我的本地主机上运行时,一切正常。我在 localhost:3000 上运行开发 React 应用程序,在 localhost:8080 上运行 Spring Boot 应用程序。在我的控制器中,我放置了 @CrossOrigin 注释,这使得 React 应用程序能够调用 Spring Boot 应用程序。这一切都很好。
但现在我想将这两个应用程序部署到 heroku 并让它们一起工作。由于它们是独立的存储库,因此我将它们分别部署到两个 Heroku 应用程序中。这些单独工作非常好。我什至可以从 Postman 对 Spring Boot 应用程序进行 API 调用。所以似乎一切正常。
但是当我尝试从 React heroku 应用程序调用 Spring Boot heroku 应用程序时,这不起作用。由于 CORS 配置不正确,可能会出现此问题。但不知何故,我就是无法让它工作。有谁知道我该如何解决这个问题?
这是我使用的控制器之一:
@CrossOrigin(origins = "https://https://localhost:3000")
@RestController
@RequestMapping("/api/klanten")
public class KlantController {
@Autowired
private KlantService klantService;
@GetMapping
public List<KlantResponse> alleKlanten() {
return this.klantService.alleKlanten();
}
}
这是我的 pom.xml 中的依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
</dependencies>
React 应用中的 package.json:
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.11.0",
"@material-ui/icons": "^4.9.1",
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^11.1.1",
"@testing-library/user-event": "^12.2.0",
"axios": "^0.21.0",
"bootstrap": "^4.5.3",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": {
"/api": {
"target": "http://localhost:8080",
"ws": true
}
}
}
最后是 axios 调用的位置:
import axios from 'axios';
const KLANTEN_REST_API_URL = ' https://localhost:8080/api/klanten';
class KlantService {
getKlanten() {
return axios.get(KLANTEN_REST_API_URL);
}
}
export default new KlantService();
我该如何解决我的问题?
【问题讨论】:
-
您已将 localhost API 端点更改为您部署的链接,对吧?
标签: reactjs spring-boot heroku cors