【问题标题】:Preflight Request failing with the window.fetch api使用 window.fetch api 的预检请求失败
【发布时间】:2016-06-01 05:47:18
【问题描述】:

让我先说它在 POSTMAN(Chrome 的附加 API 客户端)中工作。但它在我的实际应用程序中不起作用,我想知道是否有一些我忘记包含在获取请求中的东西。

我有以下要求。

(id, vzId)=>{
            var json = {id: id, vzId: vzId, };
            var request = {
                method: 'POST', 
                body: json,
                headers: new Headers({
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                })
            }
            fetch('http://localhost:8080/notification/markRead',request).then(function(response){
                return response.json();
            }).then(function(json){
                console.log(json);
            })
        }

当请求被触发时,它会返回这个错误。

OPTIONS http://localhost:8080/notification/markRead 
Fetch API cannot load http://localhost:8080/notification/markRead.   
Response for preflight has invalid HTTP status code 403

我在我的 chrome rest 客户端 (POSTMAN) 中使用了完全相同的 url 和数据,它可以正常工作,但由于某种原因,当我使用 FETCH api 时它无法正常工作。任何帮助将非常感激。

【问题讨论】:

    标签: javascript ajax fetch preflight


    【解决方案1】:

    如果有人偶然发现它并且它可以在将来帮助人们,我们找到了答案。我发布的代码没有任何问题。它在 Postman 而不是客户端上工作的原因是因为 Postman 不执行预检请求。客户端(几乎所有网站都会这样做)以 OPTIONS 方法的形式发送预检请求。后端 Spring 服务器不允许使用 options 方法。后端开发人员必须允许 OPTIONS 方法访问服务器中的特定路由,而不仅仅是 POST。

    因此,如果您在 Postman 上进行测试但无法复制行为,请记住 Postman 不会发送预检请求。

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2017-03-04
      • 2019-09-08
      • 2018-07-04
      • 2020-08-06
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多