我的中间件代码:
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === 'OPTIONS') {
res.send(200);
} else {
next();
}
});
每次我发现有人有相同的错误消息时,纠正他们问题的响应包括告诉他们像我一样设置“访问控制允许方法”。
我在前端的删除方法:
deleteSaved(url) {
// return axios.delete("https://api.mlab.com/api/1/databases/etc.", {
// params: {
// "url": url
// }
// })
// .then(function(results) {
// console.log("axios results", results);
// return results;
// });
return fetch("/saved", {
method: 'DELETE',
body: JSON.stringify({url: url}),
mode: 'cors',
cache: 'default'
}).then(function(response) {
return response;
}).then(function(data){
console.log(data);
return data;
});
}
我在那里有 fetch 和 axios ,因为我认为我在使用 axios delete 方法时遇到了问题。在开发服务器中,两个调用都正常工作。
在 axios 方法中,为了简单起见,我有我的 db API URL(为了让事情更容易工作);在 fetch 方法中,我有“/保存”,因为当我上次问这个问题时,有人评论并建议我通过我的 express 服务器代理所有数据库请求,而不是让浏览器直接连接。我尝试了一些事情(在与 create-react-app 前端关联的 package.json 中将“proxy”和“https_proxy”设置为我的 mlab api url),但我认为我并不真正理解这意味着什么。代理不起作用(“/saved”会导致应用程序 URL + /saved 上的 GET 请求出错,而不是 mlab API url),我根本无法在谷歌上找到任何关于代理请求的内容数据库通过快递服务器。
我的回复标题:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:POST,GET,OPTIONS,PUT
Access-Control-Allow-Origin:https://nyt-mern-app.herokuapp.com
Access-Control-Max-Age:1728000
Allow:POST,GET,OPTIONS,PUT
Cache-Control:no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html;charset=UTF-8
Date:Thu, 26 Oct 2017 19:34:08 GMT
Expires:Tue, 01 Feb 2000 08:00:00 GMT
Keep-Alive:timeout=5, max=99
Last-Modified:Thu, 26 Oct 2017 19:34:08 GMT
Pragma:no-cache
Server:Apache/2.4.7 (Ubuntu)
X-Frame-Options:DENY
就像我说的,一切都在本地开发环境中运行。我如何让它在部署中工作?