Code: Select all
@Configuration
public class Cors {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
< /code>
Es ist erwähnenswert, dass ich keine Spring Security verwende.
Dies ist mein Pom: < /p>
org.springframework.boot
spring-boot-starter-web
org.springframework.security
spring-security-crypto
6.1.4
org.springframework.boot
spring-boot-starter-data-jpa
org.postgresql
postgresql
42.7.2
org.projectlombok
lombok
1.18.36
provided
< /code>
Jetzt habe ich diesen Controller und die einzige Methode, die nicht funktioniert: < /p>
DTO und Controller -Methode (Methode/edit
Code: Select all
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Jacksonized
public class EditCommentRequest {
private long commentId;
private boolean isPublished;
}
@RestController
@RequestMapping("/api/comment")
public class CommentController {
final CommentService commentService;
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
@GetMapping("/get-all")
public ResponseEntity getAllComments() {
List comments = commentService.getAll();
return ResponseEntity.status(HttpStatus.OK).body(comments);
}
@PostMapping("/edit")
public ResponseEntity editComment(
@RequestBody EditCommentRequest request,
HttpSession session) {
commentService.updateCommentStatus(request, (Long) session.getAttribute(USER_ID));
return ResponseEntity.status(HttpStatus.OK).build();
}
}
Code: Select all
const handleSendEditCommentData = async (event) => {
event.preventDefault();
const requestData = {
commentId: data.id,
isPublished: isCommentShowCheckbox,
};
console.log(requestData);
try {
const response = await fetch(API_ENDPOINTS.COMMENT_EDIT, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData),
});
if (response.ok) {
onClose();
getAllData();
toast.success("Comment edited successfully.");
} else {
const errorData = await response.json();
switch (response.status) {
case 401:
toast.error(errorData.message || "401");
break;
case 404:
toast.error(errorData.message || "404");
break;
case 409:
toast.error(errorData.message || `409`);
break;
case 500:
toast.error(errorData.message || "500");
break;
default:
toast.error(`Else error`);
break;
}
}
} catch (error) {
console.error("Fetch Error:", error);
toast.error("catch error: " + error.message);
}
< /code>
Diese Methode wird aufgerufen, indem Sie auf die Schaltfläche klicken (onClick={handleSendEditCommentData}
Alle Daten, die in den Körper gesetzt werden, ist: commentid (
Code: Select all
long
Code: Select all
bool
POST http://localhost:21001/api/comment/edit net::ERR_FAILED
Fetch Error: TypeError: Failed to fetch
at handleSendEditCommentData (EditCommentModal.jsx:29:36)
at HTMLUnknownElement.callCallback2 (chunk-3F5266CN.js?v=a9e8ce0e
at Object.invokeGuardedCallbackDev (chunk-3F5266CN.js?v=a9e8ce0e
at invokeGuardedCallback (chunk-3F5266CN.js?v=a9e8ce0e
at invokeGuardedCallbackAndCatchFirstError (chunk-3F5266CN.js?v=a9e8ce0e
at executeDispatch (chunk-3F5266CN.js?v=a9e8ce0e:7046:11)
at processDispatchQueueItemsInOrder (chunk-3F5266CN.js?v=a9e8ce0e:7066:15)
at processDispatchQueue (chunk-3F5266CN.js?v=a9e8ce0e:7075:13)
at dispatchEventsForPlugins (chunk-3F5266CN.js?v=a9e8ce0e:7083:11)
at chunk-3F5266CN.js?v=a9e8ce0e:7206:20
< /code>
Hier werden zwei Anfragen gesendet, und beide erhalten keine Antwort. In Devtools sind sie rot markiert, < /p>
Zuerst - Status: CORS -Fehler, Typ: Fetch < /p>
Request URL:
http://localhost:21001/api/comment/edit
Referrer Policy:
strict-origin-when-cross-origin
RESPONE HEADERS:
none
REQUEST HEADDERS:
content-type:
application/json
referer:
http://localhost:5173/
sec-ch-ua:
"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile:
?0
sec-ch-ua-platform:
"Windows"
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
PAYLOAD:
{commentId: 5, isPublished: true}
commentId: 5
isPublished: true
< /code>
Zweitens - Status: 401, Typ: Preflight < /p>
Request URL:
http://localhost:21001/api/comment/edit
Request Method:
OPTIONS
Status Code:
401 Unauthorized
Remote Address:
[::1]:21001
Referrer Policy:
strict-origin-when-cross-origin
RESPONE HEADERS:
connection:
keep-alive
content-length:
0
date:
Sat, 08 Mar 2025 08:40:32 GMT
keep-alive:
timeout=60
REQUEST HEADDERS:
accept:
*/*
accept-encoding:
gzip, deflate, br, zstd
accept-language:
ru,ru-RU;q=0.9
access-control-request-headers:
content-type
access-control-request-method:
POST
cache-control:
no-cache
connection:
keep-alive
host:
localhost:21001
origin:
http://localhost:5173
pragma:
no-cache
referer:
http://localhost:5173/
sec-fetch-dest:
empty
sec-fetch-mode:
cors
sec-fetch-site:
same-site
user-agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36
< /code>
Postman -Antwort -Header: < /p>
Vary Origin
Vary Access-Control-Request-Method
Vary Access-Control-Request-HeadersContent-Length 0
Date Sat, 08 Mar 2025 08:59:19 GMT
Keep-Alive timeout=60
Connection keep-alive
< /code>
Die Anforderungs -URL ist korrekt. Ich habe verschiedene Optionen zum Senden von Fetch ausprobiert - sie hilft nicht, serialisiert den Körper: JSON.Stringify (RequestData) in der DTO -Klasse im Frühjahr, es scheint korrekt zu sein. Cors mit allen anderen Methoden und von anderen Controllern und aus diesem Fall funktioniert und alles ist in Ordnung, aber ich habe bereits mit dieser Methode herumgemacht und ich verstehe einfach nicht, was hier falsch ist. Und ich benutze keine Frühlingssicherheit. Außerdem sind alle URL -Pfade korrekt, die Daten sind auch korrekt im Körper am Frontend festgelegt, das DTO am Backend scheint auch korrekt zu sein, HttpSession nimmt auch die Daten richtig auf, aber dies ist nicht das Problem. Diejenigen, die es wissen, Hilfe.>