Javascript 不允许获取补丁请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34666680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:43:19  来源:igfitidea点击:

fetch patch request is not allowed

javascriptphpruby-on-railsfetch-api

提问by Kocur4d

I have two apps one is a react front end and the second one is the rails-api app.

我有两个应用程序,一个是 React 前端,第二个是 rails-api 应用程序。

I have been happily using isomorphic-fetchtill I needed to send PATCH method to the server.

我一直很高兴使用isomorphic-fetch直到我需要将 PATCH 方法发送到服务器。

I am getting:

我正进入(状态:

Fetch API cannot load http://localhost:3000/api/v1/tasks. Method patch is not allowed by Access-Control-Allow-Methods in preflight response.

but the OPTIONS response from the server includes a PATCH method in a list of Access-Control-Allow-Methods:

但是来自服务器的 OPTIONS 响应在 Access-Control-Allow-Methods 列表中包含一个 PATCH 方法:

enter image description here

在此处输入图片说明

This is how the fetch is implemented:

这是 fetch 的实现方式:

const API_URL = 'http://localhost:3000/'                                            
const API_PATH = 'api/v1/'

fetch(API_URL + API_PATH + 'tasks', {
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  method: 'patch',                                                              
  body: JSON.stringify( { task: task } )                                        
})

POST, GET, DELETE are set up pretty much the same and they are working fine.

POST、GET、DELETE 的设置几乎相同,它们运行良好。

Any idea what is going on here?

知道这里发生了什么吗?

UPDATE:

更新:

Method patch is case sensitive:

方法补丁区分大小写:

https://github.com/github/fetch/blob/master/fetch.js#L200

https://github.com/github/fetch/blob/master/fetch.js#L200

Not to sure if this is intended or a bug.

不确定这是故意的还是错误。

UPDATE 2

更新 2

This is intended and the method type PATCH needs to be case sensitive. Updating the line from fetch method to:

这是有意的,方法类型 PATCH 需要区分大小写。将 fetch 方法中的行更新为:

method: 'PATCH'

fixes the problem.

解决问题。

https://github.com/github/fetch/issues/254

https://github.com/github/fetch/issues/254

回答by drosenblatt

I had a very similar problem with reactJS front end and rails API using Rack::Cors, and adding patchto the list of allowed methods solved the problem for me.

我在使用 Rack::Cors 的 reactJS 前端和 rails API 有一个非常相似的问题,并且添加patch到允许的方法列表中为我解决了这个问题。

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :patch, :options]
  end
end

回答by Noitidart

I had this error while PATCHwas all caps. I was also getting this error with DELETEand PUTtoo. I checked the headers of my fetchand I saw a OPTIONSmethod. I was using the isomorphic-fetchlib here - https://www.npmjs.com/package/isomorphic-fetch

我在PATCH全部大写时遇到了这个错误。我也收到此错误与DELETEPUT太。我检查了我的标题,我fetch看到了一个OPTIONS方法。我在isomorphic-fetch这里使用了lib - https://www.npmjs.com/package/isomorphic-fetch

The fix for me was to add to my PHP page:

对我来说修复是添加到我的 PHP 页面:

<?php
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH');

Without this, in Firefox 53 I would keep getting the javascript error:

没有这个,在 Firefox 53 中我会不断收到 javascript 错误:

NetworkError when attempting to fetch resource.

尝试获取资源时出现 NetworkError。

The fetch I was doing was this:

我正在做的提取是这样的:

try {
    await fetch('https://my.site.com/', {
        method: 'PATCH',
        headers: { 'Content-Type':'application/x-www-form-urlencoded' },
        body: 'id=12&day=1'
    });
} catch(ex) {
    console.error('ex:', ex);
}

回答by YoJey Thilipan

use this code _method: 'PATCH'

使用此代码 _method: 'PATCH'

return (
        fetch(API_ROOT + route, {
            _method: 'PATCH',
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'Authorization': ''
            },
            data: JSON.stringify(data),
            credentials: 'include'
        })
        .then(res => res.json())
        .then(res => {
            return res
        })
        .catch(err => console.error(err))
    );

Another Way isinsert method in headers

另一种方法是在标题中插入方法

headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            '_method': 'PATCH',
            'Authorization': ''
        }

it helps you

它可以帮助你

return (
        fetch(API_ROOT + route, {
            method: 'POST',
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                '_method': 'PATCH',
                'Authorization': ''
            },
            data: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(res => {
            console.log(res);
            return res
        })
        .catch(err => console.error(err))
    );