Access to XMLHttpRequest at 'http://localhost:9999/user/login' from origin 'http://localhost:8888' 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.
时间: 2023-07-09 20:52:15 浏览: 349
这是一个CORS(跨来源资源共享)的错误。浏览器会阻止从一个域名下发出的跨域请求。在这种情况下,您的前端代码是在 localhost:8888 上运行的,但是您尝试从 localhost:9999 上请求数据。因为这两个域名不同,所以浏览器会阻止该请求。
解决这个问题的方法是在服务器端设置CORS头,以允许来自其他域名的请求。在您的情况下,您需要在 localhost:9999 上的服务器端设置 'Access-Control-Allow-Origin' 头,将其设置为 'http://localhost:8888'。这将允许来自 localhost:8888 上的请求访问您的服务器。
相关问题
Access to XMLHttpRequest at 'http://localhost:8082/api/user/login' from origin 'http://localhost:9527' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
这个错误提示是因为浏览器的同源策略(Same Origin Policy)限制了跨域请求。简单来说,浏览器不允许从一个源(域名、协议、端口)发送请求到另一个源。如果需要进行跨域请求,可以在服务端设置响应头部中的“Access-Control-Allow-Origin”字段,来允许特定的源进行访问。具体实现可以参考CORS(Cross-Origin Resource Sharing)协议。
Access to XMLHttpRequest at 'http://localhost:8081/user/login' 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
### 解决 CORS 跨域请求问题
对于从 `http://localhost:3000` 发起的 XMLHttpRequest 请求到 `http://localhost:8081/user/login` 遭遇 CORS 策略阻止的问题,可以通过配置后端来允许跨域请求。一种常见的方式是在 Spring Boot 应用程序中的控制器类或特定的方法上添加 `@CrossOrigin` 注解。
通过在目标接口处加入如下代码可以实现这一点:
```java
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@GetMapping("/user/login")
public ResponseEntity<?> login() {
// 登录逻辑...
return null;
}
}
```
上述代码片段中设置了允许来自 `http://localhost:3000` 的请求访问 `/user/login` 接口,并且启用了凭证支持[^2]。
另外,在某些情况下可能还需要调整 Web 容器级别的 CORS 设置或是利用过滤器来做更细粒度控制。如果应用使用的是 Spring Security,则需确保安全配置也适当放宽了对指定路径的权限限制以便能够响应预检请求(OPTIONS 方法),从而顺利发送实际请求[^1]。
为了使浏览器接受并处理带有认证信息(如 Cookies)的跨源请求,服务端必须显式声明 `Access-Control-Allow-Credentials` 头部为 true 并指明具体的允许来源域名而非通配符(*),这同样体现在上面给出的例子之中。
阅读全文
相关推荐

















