如何正确使用Ajax Express Csurf
forbiddenError/403 Ajax Express Csurf - how to use Csurf correctly?
嘿,伙计们,我已经做了一个星期了,我还是不太明白。
我正在构建一个相位游戏,我设置了一个记分牌使用节点,这是我第一次使用节点,我不能完全弄清楚如何使用csurf的文档是如此混乱。
ForbiddenError: invalid csrf token
at verifytoken (/Users/jorybraun/web/highscore/node_modules/csurf/index.js:269:11)
at csrf (/Users/jorybraun/web/highscore/node_modules/csurf/index.js:97:7)
at Layer.handle [as handle_request] (/Users/jorybraun/web/highscore/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jorybraun/web/highscore/node_modules/express/lib/router/index.js:312:13)
at /Users/jorybraun/web/highscore/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/Users/jorybraun/web/highscore/node_modules/express/lib/router/index.js:330:12)
at next (/Users/jorybraun/web/highscore/node_modules/express/lib/router/index.js:271:10)
at /Users/jorybraun/web/highscore/app.js:43:5
at Layer.handle [as handle_request] (/Users/jorybraun/web/highscore/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/jorybraun/web/highscore/node_modules/express/lib/router/index.js:312:13)
我得到一个403错误,每次我试图发送一个jquery post请求到我的路由得分路由从索引路由。我真的很喜欢限制对路由的访问,这样你就不能真正访问它们,除非你发出一个内部ajax请求。
这是我的app。js文件// app.js
var mongodb = require('mongodb');
var monk = require('monk');
var credentials = require('./credentials');
var db = monk(credentials.uri);
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var csrf = require('csurf');
var loadCsrf = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
var scores = require("./routes/scores");
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(loadCsrf);
app.use('/', routes);
app.use('/scores', scores);
索引路由index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { csrfToken: req.csrfToken() })
});
score route scores.js
// scores.js
var express = require('express');
var router = express.Router();
// GET scores, sorted by time
router.get('/', function(req, res) {
console.log('GET scores');
// Get the database object we attached to the request
var db = req.db;
// Get the collection
var collection = db.get('scores');
// Find all entries, sort by time (ascending)
collection.find({}, { sort: { score : 1 } }, function (err, docs) {
if (err) {
// Handle error
console.error('Failed to get scores', err);
res.status(500).send('Failed to get scores');
} else {
// Respond with the JSON object
res.json(docs);
}
});
});
// GET a number of top scores
// (the /top route without a number won't work unless we add it)
router.get("/top/:number", function(req, res) {
console.log("GET top scores");
// Read the request parameter
var num = req.params.number;
var db = req.db;
var collection = db.get("scores");
// Get all scores, but limit the number of results
collection.find({}, { limit: num, sort: { score : 1 } }, function(err, docs) {
if (err) {
console.error("Failed to get scores", err);
res.status(500).send("Failed to get scores");
} else {
res.json(docs);
}
});
});
// POST a score
router.post("/", function(req, res) {
module.exports = router
console.log("POST score");
var name = req.body.name;
var score = Number(req.body.score);
var email = req.body.email;
if (!(name && score)) {
console.error("Data formatting error");
res.status(400).send("Data formatting error");
return;
}
var db = req.db;
var collection = db.get("scores");
collection.insert({
"name": name,
"score": score,
"email": email
}, function(err, doc) {
if (err) {
console.error("DB write failed", err);
res.status(500).send("DB write failed");
} else {
// Return the added score
res.json(doc);
}
});
});
module.exports = router;
在Phaser画布中的Ajax请求,函数submit() {
var name = prompt("Please enter your name");
var email = prompt("Please enter your email adress, this will not be featured on the scoreboard");
var csrf_token = "#{csrfToken}";
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});
$.post({
url: 'http://localhost:3000/scores/',
data: {
name: name,
email: email,
score: score
},
success: function(data) {
console.log('Score posted', data);
},
error: function(xhr, msg) {
console.error('AJAX error', xhr.status, msg);
}
});
}
这会导致如下错误:
n.ajaxTransport.l.cors.a.crossDomain.send @ jquery.min.js:4
n.extend.ajax @ jquery.min.js:4
n.each.n.(anonymous function) @ jquery.min.js:4
submit @ game.js:263
c.SignalBinding.execute @ phaser.min.js:8
c.Signal.dispatch @ phaser.min.js:8
c.Button.onInputUpHandler @ phaser.min.js:12
c.SignalBinding.execute @ phaser.min.js:8
c.Signal.dispatch
我已经尝试了很多不同的选择,但如果有人能帮我找到一个简单的解决方案,那将是惊人的!
谢谢
好的,所以我弄清楚了为什么这不起作用-我已经通过了大量的堆栈溢出和教程,每个人都说要在标题中设置它。我没有测试过这个,但我认为你需要使用不同的csrf令牌的头部工作。这个令牌在正文中设置:
res.render('index', { csrfToken: req.csrfToken() })
在body中寻找一个以_csrf为键的键对值。
var csrf_Token = getCsrfToken();
function getCsrfToken() {
var metas = document.getElementsByTagName('meta');
for (i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == "_csrf") {
return metas[i].getAttribute("content");
}
}
return "";
}
$.post({
url: 'http://localhost:3000/scores/',
data: {
_csrf: csrf_Token,
name: name,
email: email,
score: score
},
success: function() {
console.log('Score posted');
},
error: function(xhr, msg) {
console.error('AJAX error', xhr.status, msg);
}
});
如果有人能帮助我找到另一种方法来完成这项工作,我会喜欢它,因为通过元标记将令牌传递给客户端似乎并不是最好的方法。
相关文章:
- 使用Express捕获参数
- 从模块内部访问Express装载路径
- 在Nodejs中Express输入DEBUG=app时权限被拒绝/bin
- 如何使用Node/Express显示有关特定错误的自定义html页面
- 发送json对象或使用express路由呈现视图
- renderReact/Rect Router+Node/Express.js的服务器端/同构渲染中未定义renderP
- 为什么不't Express呈现我的React应用程序
- Express服务器中语言子域的最佳实践
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- Nodejs和express路由,如何处理客户端的承诺
- node.js和express中的异常处理
- 什么'在Express中路由时,应用程序级中间件和路由器级中间件之间的区别是什么
- 如何在不重新加载的情况下提交表单,并使用Node+Express将数据传递回同一页面
- Express.js:在用户发帖时获取用户的引荐来源网址
- 使用express.具有多个url和可选参数的Router()
- 使用connect vhost为多个express.js应用程序提供服务
- Express.js和multer:如何知道文件何时全部上传
- Node Express和csurf-403(禁止)无效的csrf令牌
- 无法摆脱ForbiddenError:无效的csrf令牌在express与csurf
- 如何正确使用Ajax Express Csurf