我试图获得一个使用MEAN堆栈的简单示例,我注意到我的DELETE请求在Firefox中不起作用。我相信这是由于CORS造成的。
[当我单击一个链接以向我的ExpressJS后端提交带有angularJS的DELETE请求时,我看到首先调用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); } } } }
我的浏览器网址是
http://localhost:63342/express_example/public/#/
更新
我的服务器通过以下方式响应预检请求:
服务器控制台:选项/ notes / 53568807130e0f701f000001 200 0ms-2bGET / notes 304 8ms
浏览器控制台:
我试图获得一个使用MEAN堆栈的简单示例,我注意到我的DELETE请求在Firefox中不起作用。我相信这是由于CORS造成的。当我单击链接以提交DELETE ...
所以这对CORS来说不是问题,您的代码中有一个小逻辑错误。
除非您的Express处理程序实际上删除了该对象,否则您不应该自动回复204响应。您没有在此处发布处理程序,但是在Mongoose / MongoDB中,它可能看起来像:
您正在执行的操作的问题是,它将打开您的服务器以接收来自所有域的请求。之前失败的原因是,如果您注意到请求标头具有主机localhost: 3000
,但是您的服务器仅接受来自localhost: 63342
]的请求,
除非您担心其他人制作的应用程序正在运行将在客户端计算机上运行的服务器,否则您不必担心会向所有域开放。任何人都可以使用提琴手或任何REST客户端(例如Advanced REST Client)访问服务器。