【问题标题】:GET request working on postman but not in browserGET请求在邮递员上工作但不在浏览器中
【发布时间】:2020-05-18 15:31:08
【问题描述】:

我遇到了一个奇怪的 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 请求。 唯一这个和另一个工作之间的区别是它有一个'变量'可以传入并有一个设定的路线:

    [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】:

要解决 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();
    }
}

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 2019-10-02
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多