我有两个应用程序之一是反应前端,第二个是在轨道的API的应用程序。
我一直愉快地使用isomorphic-fetch直到我需要发送PATCH方法到服务器。
我正进入(状态:
Fetch API cannot load http://localhost:3000/api/v1/tasks. Method patch is not allowed by Access-Control-Allow-Methods in preflight response.
但来自服务器的响应中包括在访问控制允许的方法的列表的方法PATCH:
这是怎么获取实现:
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设置了几乎相同的,他们都工作正常。
任何想法是怎么回事?
更新:
法补丁是区分大小写的:
https://github.com/github/fetch/blob/master/fetch.js#L200
不知道这是有意或一个错误。
更新2
这是为了与方法类型PATCH需要是大小写敏感的。更新从取方法的行:
method: 'PATCH'
解决了这个问题。
我曾与reactJS前端的非常类似的问题,并使用机架::一个Cors轨API,并添加patch
到允许的方法列表中解决了这个问题对我来说。
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :patch, :options]
end
end
我有这个错误而PATCH
是全部大写。我也收到此错误与DELETE
和PUT
了。我检查了我fetch
的头,我看到一个OPTIONS
方法。我用的是isomorphic-fetch
LIB这里 - https://www.npmjs.com/package/isomorphic-fetch
对我来说,伦敦定盘添加到我的PHP页面:
<?php
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH');
没有这一点,在Firefox 53我就不断收到JavaScript错误:
NetworkError当试图获取资源。
该取我做的是这样的:
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);
}
使用此代码_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))
);
另一种方式是在头插入方法
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'_method': 'PATCH',
'Authorization': ''
}
它可以帮助你
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))
);