为api请求设置代理

时间:2019-10-11 17:45:38

标签: java reactjs rest api request

我正在尝试从后端获取数据。我正在使用Spring Boot并做出反应。当我尝试获取数据时出现此错误

Access to fetch at 'http://localhost:8080/getText' from origin 'http://localhost:3000' has been 
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource 
with CORS disabled.

因此,经过研究,我意识到我必须设置代理。所以我在我的package.json文件中添加了代理,现在看起来像这样

{
 "name": "web-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.10.2",
    "react-dom": "^16.10.2",
    "react-scripts": "3.2.0"
},
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
},
"proxy": "http://localhost:8080/",
"eslintConfig": {
  "extends": "react-app"
},
"browserslist": {
  "production": [
    ">0.2%",
    "not dead",
    "not op_mini all"
  ],
  "development": [
    "last 1 chrome version",
    "last 1 firefox version",
    "last 1 safari version"
  ]
 }
}

仍然出现相同的错误。这是我使用的后端和前端。反应方法-

componentDidMount(){
    fetch("http://localhost:8080/getText")
        .then(response => response.json())
        .then(data => console.log(data))
}

和Spring控制器-

@RestController
public class TextController {

  @Autowired
  private TextService textService;

   @RequestMapping(path = "/getText", method = RequestMethod.GET)
   public ResponseEntity<?> getAllText(){
      List<String> result = textService.getAllText();
      return new ResponseEntity(result, HttpStatus.OK);
   }

}

0 个答案:

没有答案