Javascript 禁止错误/403 Ajax Express Csurf-如何正确使用Csurf?

Javascript 禁止错误/403 Ajax Express Csurf-如何正确使用Csurf?,javascript,ajax,node.js,express,csrf,Javascript,Ajax,Node.js,Express,Csrf,嘿,伙计们,我已经做了一个星期了,我还不太明白 我正在构建一个phaser游戏,我使用node设置了一个记分板,这是我第一次使用node,我不太明白如何使用csurf,因为文档太混乱了 ForbiddenError: invalid csrf token at verifytoken (/Users/jorybraun/web/highscore/node_modules/csurf/index.js:269:11) at csrf (/Users/jorybraun/web/

嘿,伙计们,我已经做了一个星期了,我还不太明白

我正在构建一个phaser游戏,我使用node设置了一个记分板,这是我第一次使用node,我不太明白如何使用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)
每次尝试从索引路由向路由分数路由发送jquery post请求时,我都会收到403错误。我真的很想限制对路由的访问,这样您就不能真正访问它们,除非您发出内部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请求, 函数提交(){

这将导致如下错误:

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
我尝试了很多不同的选择,但如果有人能帮我找到一个简单的解决方案,那将是惊人的


谢谢你

好的,所以我明白了为什么这不起作用-我已经阅读了大量的StackOverflow和教程,每个人都说要在标题中设置它。我还没有测试过这一点,但我认为你需要使用不同的csrf令牌才能使头部起作用。此令牌设置在主体中:

res.render('index', { csrfToken: req.csrfToken() })
它正在寻找一个密钥对值,其中_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);
        }
    });
var csrf_Token=getCsrfToken();
函数getCsrfToken(){
var metas=document.getElementsByTagName('meta');

对于(i=0;我已经发布了与此问题类似的答案
    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);
        }
    });