我是node.js和express的新手,我正试图用一个令牌来保护一些url。我正确地生成了令牌,但是当我使用此令牌发布表单时,我的浏览器中出现错误,此文本为“无法发布/处理”,其中/ process是我从表单发送数据的URL。在我的控制台中,我没有任何错误。所以,我不知道发生了什么或我做错了什么:(
代码分为三个文件,主文件名为(index.js),其中我需要第二个文件(routes-api.js)和带有表单的html文件。
index.js
//Creación de un servidor con express
const express = require("express");
const app = express(); //Inicializamos express
//Accedemos a otros módulos
const morgan = require("morgan");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const cookieParser = require('cookie-parser');
//Accedemos a propiedades de configuración
const config = require("./config");
//Rutas
const routes = require("./routes");
const routesAPI = require("./routes-api");
//Settings
app.set("app-name", config.server);
app.set("port", config.port);
app.set("super-secret", config.secret);
//Middlewares
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan("dev")); //Log request to the console
app.use(cookieParser());
app.use((req, res, next) => {
console.log("Pasamos por la segunda función!!!");
next();
});
//Routing
app.use("/api", routesAPI);
app.use(routes);
//Server
app.listen(app.get("port"), () => {
console.log("Servidor " + app.get("app-name") + " escuchando!!!");
}); //Creamos el servidor con express
路由api.js
const csrf = require('csurf');
const path = require("path");
const bodyParser = require("body-parser");
const express = require("express");
const router = express.Router();
// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });
router.get("/", csrfProtection, (req, res) => {
console.log("crsf: " + req.csrfToken());
res.sendFile(path.join(__dirname + '/send.html'), { csrfToken: req.csrfToken() });
});
router.post('/process', parseForm, csrfProtection, function(req, res) {
console.log("csrf: " + req.body._csrf + " color: " + req.body.favoriteColor);
res.send('data is being processed');
});
module.exports = router;
send.html
<form action="/process" method="POST">
<input type="text" name="_csrf" value="{{csrfToken}}">
Favorite color: <input type="text" name="favoriteColor">
<button type="submit">Submit</button>
</form>
当我将表单发送到服务器时,出现错误“无法POST /处理”,我做错了什么?