我对nodejs相当新!我写了一个代码来避免csrf,但是出了点问题,我总是得到无效csrf令牌的错误。有谁能够帮我? 这是我的nodejs文件的代码:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var csrfProtection = csrf({ cookie: true })
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var app = express();
app.use(cookieParser())
app.use(express.static('public'));
app.get('/index.html', csrfProtection, function (req, res) {
res.render('send', { csrfToken: req.csrfToken() });
})
app.post('/process_post', urlencodedParser, csrfProtection, function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
var server = app.listen(8081, 'localhost', function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
这是我的html文件的代码:
<form action = "http://127.0.0.1:8081/process_post" method = "POST">
<input type="hidden" name="_csrf" value="<%=csrfToken%>">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>
我认为将令牌设置为隐藏值是有道理的,因为当我尝试在浏览器中查看页面的源代码时,值仍为&lt;%= csrfToken%&gt;虽然它应该设置为随机值。