您要使用csrf进行代码创建和修改。但ForbiddenError:无效的CSRF令牌。 我不知道为什么会这样。
到目前为止的代码如下:
app.js
const _Express = require('express');
const _Nunjucks = require('nunjucks');
const _Logger = require('morgan');
const _BodyParser = require('body-parser');
const _CookieParser = require('cookie-parser');
const _Db = require('./models');
// DB authentication
_Db.sequelize.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
return _Db.sequelize.sync();
})
.then(() => {
console.log('DB Sync complete.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const _Admin = require('./routes/admin');
const _Contacts = require('./routes/contacts');
const _App = _Express();
const _Part = 3000;
_Nunjucks.configure('template', {
autoescape: true,
express: _App
});
_App.use(_Logger('dev'));
_App.use(_BodyParser.json());
_App.use(_BodyParser.urlencoded({ extended: false }));
_App.use(_CookieParser());
_App.get('/', function( _ ,res){
res.send('first _App');
});
console.log(__dirname);
_App.use('/admin',_Admin);
_App.use('/contacts',_Contacts);
_App.use('/uploads', _Express.static('uploads'));
_App.listen(_Part,function(){
console.log('Express listening on Port',_Part);
});
routes / admin.js
...
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
const _Routes = _Express.Router();
...
_Routes.get('/products/write', csrfProtection, function ( req , res) {
res.render('admin/form.html',{ csrfToken : req.csrfToken() });
});
_Routes.post('/products/write', csrfProtection,(req, res) => {
_Models.Products.create(
//{
req.body
// name : req.body.name,
// price : req.body.price ,
// description : req.body.description
//}
).then(() => {
res.redirect('/admin/products');
});
});
form.html
{% set title = "insert" %}
{% extends "layout/base.html" %}
{% block content %}
<form action="" method="post" enctype = "multipart/form-data">
<input type="hidden" name="_csrf" value="{{ csrfToken }}" />
<table class="table table-bordered">
<tr>
<th>name</th>
<td><input type="text" name="name" class="form-control" value="{{HTMLProducts.name}}"/></td>
</tr>
<tr>
<th>price</th>
<td><input type="text" name="price" class="form-control" value="{{HTMLProducts.price}}" /></td>
</tr>
<tr>
<th>memo</th>
<td><input type="text" name="description" class="form-control" value="{{HTMLProducts.description}}"/></td>
</tr>
</table>
<button class="btn btn-primary">enter</button>
</form>
{% endblock %}
csrfToken值是通过正常路径接收的。但是会发生错误。
ForbiddenError:无效的CSRF令牌