首页 > 解决方案 > 使用 POSTMAN 的跨域请求 -401

问题描述

目前正在开发 Spring Boot 后端API服务。该API需要两个值,一个用于路径变量,另一个用于请求正文。使用POSTMAN应用程序发出请求。

在此处输入图像描述

当我点击发送按钮时,它将显示如下

{
    "timestamp": "2020-07-31T05:57:15.178+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "No message available",
    "path": "/Service/api/ea/saveConfig/$%7Bhost%7D"
}

控制器类

我添加了像打击这样的跨源注释

编辑1

@CrossOrigin(origins = "http://localhost:8000")
@RestController
@RequestMapping("/api/ea")
public class ServiceConfigController
{
    @PostMapping(value = "/saveConfig/{host}", produces = "application/json")
        public ResponseEntity<JsonNode> saveConfig(@PathVariable String host,
                @RequestBody JsonNode data) throws JsonProcessingException
        {
            try
            {
                ResponseEntity<JsonNode> result = configService.saveConfiguration(host, data);

                return result;
            }

            catch (Exception e)
            {           
                return new ResponseEntity<>(data, HttpStatus.INTERNAL_SERVER_ERROR);
            }
    }
}

如果我们从POSTMAN发出请求,那么交叉来源是什么。我尝试了一些东西,但没有帮助。

请提出一个有效的解决方案。

标签: springspring-bootspring-securitypostman

解决方案


POSTMAN 路径变量应该是 {{host}} 而不是 ${host}。请分享您的 pom xml。最好的猜测是你可以使用 spring security 来保护你的 API。请从您的 pom 中删除依赖项,然后重试。

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

如果 spring security 是必须的,您可以尝试将 Auth 添加到您的 POSTMAN 并重试。用户名是用户,密码在您的控制台中生成并打印。例如,

2020-07-31 15:19:01.727  INFO 3296 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 
Using generated security password: ae4b7465-ab44-416d-96e3-8d122f755e04
2020-07-31 15:19:01.811  INFO 3296 --- [           main]

邮递员身份验证屏幕


推荐阅读