CORS无法在Firefox中运行

我试图得到一个简单的例子与MEAN堆栈工作,我注意到我的DELETE请求在Firefox中不起作用。 我相信这是由于CORS。

当我点击一个链接提交DELETE请求与angularJS到我的ExpressJS后端,我看到一个GET请求被首先调用,然后调用实际的DELETE请求,但DELETE请求永远不会结束。

删除请求

这一切似乎工作在Chrome没有问题。 没有意外的GET请求调用,DELETE请求实际上完成。 我怎样才能使这个工作在Firefox?

快递部分为Cors:

// CORS Stuff in app.js app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Content-Length"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); if(req.method == 'OPTIONS') { res.send(204); //next(); } else { next(); } //res.send(200); }); app.get('/notes', note.get(db)); app.post('/notes', note.create(db)); app.put('/notes/:id', note.update(db)); app.delete('/notes/:id', note.delete(db)); 

然后我有这个note.js文件

 exports.delete = function(db) { return function(req, res) { console.log('were in delete middleware'); //var note_id = req.body.id; var note_id = req.params.id; console.log("note_id = "+note_id); var collection = db.get('notes'); collection.remove( {_id: note_id} ), function(err, doc) { console.log('were in delete middleware function'); // If it failed, return error if (err) { console.log('were in delete error'); res.send("There was a problem deleting that note from the database."); } else { console.log('were in delete success'); res.send(200); } } } } 

我的浏览器URL是http://localhost:63342/express_example/public/#/

更新

我的服务器响应预检请求:

服务器控制台:OPTIONS / notes / 53568807130e0f701f000001 200 0ms – 2b GET / notes 304 8ms

浏览器控制台 在这里输入图像描述

所以这不是CORS的问题,你的代码中有一个小的逻辑错误。

问题出在这个电话上:

 collection.remove( {_id: note_id} ), 

我将假设它期望第二个参数是一个callback函数,这可能是你为什么用a而不是a结束语句的原因; 。 你也定义callback函数作为下一个语句,但从来没有使用它。 因此,为什么删除永远不会结束,callback从来没有被调用,因为它没有被传递到collection.remove()调用。

试试这个:

 var collection = db.get('notes'); collection.remove( {_id: note_id}, function(err, doc) { console.log('were in delete middleware function'); // If it failed, return error if (err) { console.log('were in delete error'); res.send("There was a problem deleting that note from the database."); } else { console.log('were in delete success'); res.send(200); } }); 

不知道为什么这可以在Chrome浏览器中使用,而不是在Firefox中使用,但是如果必须猜测的话,那么Chrome可能会从您的CORS处理程序中获取204,并且只能接受它。 这只是一个猜测,因为你上面发布的代码永远不会返回一个响应回到客户端。

除非您的Express处理程序已经实际删除了该对象,否则您可能不应该使用204响应自动回复。 你没有在这里发布你的处理程序,但使用Mongoose / MongoDB,它可能看起来像:

 app.delete('/records/:recordId', function(req, res){ req.record.remove(function(err){ if (err) { console.log("Error deleting record"); return res.json(500, {error: err}); } return res.json(204); }); }); 

你在做什么的问题是,它打开你的服务器来自所有域的请求。 之前失败的原因是,如果您注意到请求标头有一个localhost: 3000主机,但您的服务器只接受来自localhost: 63342请求localhost: 63342

除非您担心别人正在创build将在客户端计算机上运行的服务器,否则您可能不需要担心将其开放给所有域。 任何人都可以使用Fiddler或任何REST客户端(如Advanced REST Client)来访问服务器。