GET请求适用于邮递员,但不适用于浏览器

问题描述 投票:0回答:1

我遇到了一个我遇到的GET请求的奇怪问题。

我正在从ASP.Net应用程序中调用一个GET请求,该请求在邮递员中可以正常工作,但没有命中我的userGETReq.onload。

function getUser(username){
userGETReq.open("GET", userURL + "/" + username);
userGETReq.send();

userGETReq.onload = () => {if(userGETReq.status === 200){//cool stuff }}

我正在浏览器中的本地主机上运行-从返回false的表单中调用启动该函数的功能。

 <form onsubmit="login(this); return false">

邮递员

Picture of successful postman response for the GET request

我从同一应用程序收到其他有效的GET请求。与其他有效方法之间的only区别在于,它具有传入的“变量”并具有设置的路由:

    [Route("api/User/{username}")]
    public List<User> Get(string username)

这是我的CORS的设置方式

这是问题

CORS:

        EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");
        config.EnableCors(cors);

任何帮助将不胜感激!

我得到的警告:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:56390/api/user/test3. (Reason: CORS request did not succeed).
asp.net xmlhttprequest cors postman
1个回答
0
投票

要解决CORS问题,您可以按如下所示在服务中编写另一种方法

每次进行服务调用时,首先触发OPTIONS来检查是否允许该服务调用,并且一旦OPTIONS返回允许,就会调用实际方法//在这里,您可以在HEADER_AC_ALLOW_ORIGIN

下添加呼叫主机的URL或客户端URL
@OPTIONS
@Path("/yourservice/")
@LocalPreflight
public Response options() {
    String origin = headers.getRequestHeader("Origin").get(0);
    LOG.info(" In options!!!!!!!!: {}", origin);
    if ("http://localhost:4200".equals(origin)) {
        return Response.ok()
                       .header(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS, "GET,POST,DELETE,PUT,OPTIONS")
                       .header(CorsHeaderConstants.HEADER_AC_ALLOW_CREDENTIALS, "false")
                       .header(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN, "http://localhost:4200") 
                       .header(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS, "content-type")
                       .build();
    } else {
        return Response.ok().build();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.