1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.js + ExpressでSCRF(csurf)とmulterが同時に使えない場合の対処

Posted at

ハマってしまったので覚書。
multerはscrfの前に書く必要があるよう。

公式のSimple express exampleコードを参考にしてrouterファイルを使う場合

app.js
const cookieParser = require('cookie-parser')
const csrf = require('csurf')
const bodyParser = require('body-parser')
const express = require('express')

// create express app
const app = express()

// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())

//router
app.use('/', index);
index.js
const express = require('express');
const multer = require('multer');
const router = express.Router();
const upload = multer({dest: 'uploads/', limits: {fileSize: 5000000}});
//router内側で宣言
const bodyParser = require('body-parser');
const csrf = require('csurf');

// setup route middlewares
const csrfProtection = csrf({ cookie: true });
const parseForm = bodyParser.urlencoded({ extended: false });

router.get('/form',csrfProtection,function(req,res){
    // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
}

//multerはscrfの前!
router.post('/process',upload.fields([{name: 'image'}]),parseForm,csrfProtection, function (req, res, next) {
    res.send('data is being processed')
}

たったこれだけだが予想以上にハマってしまったので忘れないようにメモ。
app.js内でapp.use(csrf({ cookie: true })する方が楽で、その場合はその前にmulterを入れるのだろうが
app.use(multer())を使ったことが無いのでとりあえずこっちで。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?