从源“http://localhost:4200”访问“localhost:8088/user/”的 XMLHttpRequest 已被 CORS 策略阻止 [重复]

Posted

技术标签:

【中文标题】从源“http://localhost:4200”访问“localhost:8088/user/”的 XMLHttpRequest 已被 CORS 策略阻止 [重复]【英文标题】:Access to XMLHttpRequest at 'localhost:8088/user/' from origin 'http://localhost:4200' has been blocked by CORS policy [duplicate] 【发布时间】:2021-12-26 14:05:54 【问题描述】:

我正在使用 Spring Boot 和 Angular。我使用了跨源注释,提到了我的 localhost 的 Angular 端口,但尽管如此我收到以下错误

我的 Spring 启动代码如下

我的模型课

公共类用户

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String userName;
private String password;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private boolean enabled = true;
private String profile;

控制器类如下

package com.exam.portal.controller;

import com.exam.portal.entity.Role;
import com.exam.portal.entity.User;
import com.exam.portal.entity.UserRole;
import com.exam.portal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Set;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/user")
public class UserController 

    @Autowired
    private UserService userService;

    @PostMapping("/")
    public User createUser(@RequestBody User user) throws Exception 

        Set<UserRole>roles = new HashSet<>();
        Role role = new Role();
        role.setRoleId(44L);
        role.setRoleName("NORMAL");

        UserRole userRole = new UserRole();
        userRole.setUser(user);
        userRole.setRole(role);
        roles.add(userRole);
        return userService.createUser(user,roles);
    

    @GetMapping("/username")
    public User getUser(@PathVariable("username")String userName)
    return userService.getUserByUserName(userName);
    

    @DeleteMapping("/id")
    public void deleteUser(@PathVariable("id")Long id)
         userService.deleteUser(id);
    

Angular 服务代码

constructor(private http : HttpClient)  
  public addUser(user:any)
    console.log("user data is ",user);
    return this.http.post(`$baseURL/user/`,user);
    
  

【问题讨论】:

您似乎缺少baseURL 中的协议。 谢谢!我似乎错过了它。它起作用了。 baseURL之前使用http:// 【参考方案1】:

您的变量 baseURL 似乎缺少 localhost:8088 之前的 http://

【讨论】:

以上是关于从源“http://localhost:4200”访问“localhost:8088/user/”的 XMLHttpRequest 已被 CORS 策略阻止 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从源“http://localhost:4200”访问“localhost:8088/user/”的 XMLHttpRequest 已被 CORS 策略阻止 [重复]

带有 Angular 的 Spring Boot。从源“http://localhost:4200”访问“http://localhost:8080/”的 XMLHttpRequest 已被 CORS

从源“http://localhost:4200”访问“http://localhost:9090/api/auth/produits/files”的 XMLHttpRequest 已被 CORS 策

从源“http://localhost:4200”访问“”处的 XMLHttpRequest 已被 CORS 阻止。我无权访问服务器

从源“http://localhost:4200”访问“https://exam.com/api/Uni/GetAll”的 XMLHttpRequest 已被 CORS 策略阻止

来源 'http://localhost:4200' 已被 CORS 策略阻止