Spring Boot+React笔记CRUD项目Fetch请求CORS失败求助
笔记CRUD应用CORS错误排查求助
我开发了一个Spring Boot后端+MySQL数据库的React笔记CRUD应用,Postman调用API能正常操作数据库,但React前端发起Fetch请求时出现CORS错误:
Access to fetch at 'http://localhost:8080/api/note' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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. POST http://localhost:8080/api/note net::ERR_FAILED Uncaught (in promise) TypeError: Failed to fetch
相关代码
Controller类(Java)
@RestController @RequestMapping(path = "api/note") @CrossOrigin(origins = "*") public class NoteController { @Autowired NoteService noteService; @PostMapping(path = "/") public ResponseEntity<NoteModel> createNote(@RequestBody NoteModel newNote) { return new ResponseEntity<>(this.noteService.createNote(newNote), HttpStatus.OK); } @PutMapping(path = "/{id}") public ResponseEntity<NoteModel> updateNote(@RequestBody NoteModel note, @PathVariable Long id) throws Exception { return new ResponseEntity<>(this.noteService.updateNote(note, id), HttpStatus.OK); } @GetMapping(path = "/") public ResponseEntity<List<NoteModel>> findAllNotes(){ return new ResponseEntity<>(this.noteService.findAllNotes(), HttpStatus.OK); } @DeleteMapping(path = "/{id}") public ResponseEntity<String> createNote(@PathVariable Long id) throws Exception { this.noteService.deleteNote(id); return new ResponseEntity<>("Note deleted successfully", HttpStatus.CREATED); } }
React请求组件
import React from 'react' import closeButton from '../images/close-button.png' import { useState } from 'react'; function Popup(props) { const [title, setTitle] = useState(""); const [content, setContent] = useState(""); const handleClick=(e) => { e.preventDefault() const note = {title, content} console.log(title, content) fetch("http://localhost:8080/api/note", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(note) }).then(()=>{ console.log("New note added!") }) setTitle("") setContent("") props.setTrigger(false) } const handleExit=(e) => { e.preventDefault() props.setTrigger(false) setTitle("") setContent("") } return (props.trigger) ? ( <div className="popup"> <div className="inner-popup"> <img src={closeButton} className="close-btn" onClick={handleExit} alt="Close"/> <h2 className="popup-title">Add new note</h2> <form> <div className="form-title"> <label>Title</label> <input type="text" id="form-title-input" name="form-title-input" placeholder="Note Title" value={title} onChange={(e)=>setTitle(e.target.value)} /> </div> <div className="form-content"> <label>Content</label> <textarea id="note-content-txtf" name="note-content" placeholder="Note about something..." value={content} onChange={(e)=>setContent(e.target.value)} /> </div> <div className="form-buttons"> <button className="btn box-shw btn-cancel" onClick={handleExit}>Cancel</button> <button className="btn box-shw btn-confirm" onClick={handleClick}>Confirm</button> </div> </form> </div> </div> ) : ""; } export default Popup
已尝试的解决方法
- 在Java控制器类添加
@CrossOrigin(origins="*") - 在React的Fetch请求中设置
mode:"no-cors" - 添加自定义
CorsConfiguration类 - 在请求头中设置
Access-Control-Allow-Origin:"*"
以上方法均未解决问题,求可行的解决方案。
内容的提问来源于stack exchange,提问作者ramalandajo
相关产品推荐
相关产品推荐

