Express 如何启用删除请求?
由于CORS,我无法允许从我的API服务器删除Express 如何启用删除请求?,express,cors,Express,Cors,由于CORS,我无法允许从我的API服务器删除请求 server.js 我收到一个控制台错误,它说: XMLHttpRequest无法加载http://localhost:8080/api/users/57f5036645c04700128d4ee0. 飞行前响应中的访问控制允许方法不允许方法删除 如何启用删除请求,就像获取、放置和发布请求一样?通过简单地使用npm的包并启用所有cors请求,通过简单地替换 // enable CORS app.use(function (req, res, n
请求
server.js
我收到一个控制台错误,它说:
XMLHttpRequest无法加载http://localhost:8080/api/users/57f5036645c04700128d4ee0. 飞行前响应中的访问控制允许方法不允许方法删除
如何启用删除请求,就像获取
、放置
和发布
请求一样?通过简单地使用npm的包并启用所有cors请求,通过简单地替换
// enable 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");
next();
});
与
app.use(require('cors')());
但是我仍然不确定magic cors软件包在引擎盖下做了什么来让它工作。您的一个标题没有正确设置,因此
res.header("Access-Control-Allow-Methods", "GET", "PUT", "POST", "DELETE", "OPTIONS");
把它当作
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
但是你说得对,使用npm软件包更简单。我解决了这个问题,没有添加新的软件包,只是添加了这一行
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
请注意,我在一个字符串中使用逗号分隔允许的方法。
完整的函数如下所示:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
@UmakantMane我更新了我的前端请求,如下所示:$.ajax({async:true,crossDomain:true,url:“…”,方法:'DELETE',标题:{'content type':'application/x-www-form-urlencoded','Authorization':'…})代码>,但没有help@UmakantMane发表评论而不是建议
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});