Express.js POST 请求在安装express-formidable 后不起作用
我安装了express-formidable,突然代码中的所有发布请求都停止工作了。即使我提出请求,也没有任何反应。我通过卸载express-formidable再次尝试,效果很好。可能是什么问题?
这是我的代码,
const express = require("express");
const bodyParser = require("body-parser");
const mailchimp = require("@mailchimp/mailchimp_marketing");
const ejs = require("ejs");
const _ = require("lodash");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const { request } = require("express");
require("dotenv/config");
var formidable = require("express-formidable");
var eventsData = require("./events.json");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(formidable());
app.use(express.static("public"));
app.set("view engine", "ejs");
mailchimp.setConfig({
apiKey: process.env.MAILCHIMP_API,
server: process.env.MAILCHIMP_SERVER,
});
app.use(
session({
secret: "SLIITMOZILLA2022",
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
console.log("connected");
}
);
const blogSchema = new mongoose.Schema({
title: String,
content: String,
url: String,
image: String,
});
const eventSchema = new mongoose.Schema({
title: String,
description: String,
date: Date,
location: String,
img: String,
url: String,
});
const userSchema = new mongoose.Schema({
username: String,
googleId: String,
});
userSchema.plugin(passportLocalMongoose);
Blog = new mongoose.model("Blog", blogSchema);
Event = new mongoose.model("Event", eventSchema);
User = new mongoose.model("User", userSchema);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/compose", //ONLY FOR LOCAL USE
// callbackURL: "https://sliitmcc.herokuapp.com/auth/google/compose",
},
function (accessToken, refreshToken, email, done) {
User.findOne(
{ googleId: email.id, username: email.emails[0].value },
function (err, user) {
if (err) {
return done(err);
}
//No user was found... so create a new user with values from Facebook (all the profile. stuff)
else {
//found user. Return
return done(err, user);
}
}
);
}
)
);
app.get("/", (req, res) => {
Blog.find(
{},
{
_id: 0,
},
{ sort: { _id: -1 } },
function (err, items) {
res.render("index", { blog: items });
}
);
});
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["email", "profile"] })
);
app.get(
"/auth/google/compose",
passport.authenticate("google", { failureRedirect: "/login" }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/compose");
}
);
app.get("/blogs", (req, res) => {
res.render("blogs");
});
app.get("/events", (req, res) => {
res.render("events", { eventData: eventsData });
});
app.get("/contact_us", (req, res) => {
res.render("contact_us");
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/invaliduser", (req, res) => {
res.render("invaliduser");
});
app.get("/compose", (req, res) => {
if (req.isAuthenticated()) {
res.render("compose");
} else {
res.redirect("/login");
}
});
app.post("/", (req, res) => {
const userEmail = req.body.email;
const listId = process.env.MAILCHIMP_LIST_ID;
const subscribingUser = {
email: userEmail,
};
console.log("post working");
async function run() {
try {
const response = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.email,
status: "subscribed",
});
console.log(" Succesfully Subscribed!");
res.redirect("/");
} catch (err) {
res.render("failure");
console.log(err.status);
}
}
run();
});
app.post("/blogs", async function (req, res) {
var limit = 6;
var startFrom = parseInt(req.fields.startFrom);
Blog.find(
{},
{
_id: 0,
},
{ sort: { _id: -1 }, skip: startFrom, limit: limit },
function (err, items) {
res.json({ blog: items });
}
);
});
app.post("/compose", (req, res) => {
const post = new Blog({
title: _.capitalize(req.body.title),
content: _.capitalize(req.body.content),
url: req.body.url,
image: req.body.image,
});
post.save((err) => {
if (!err) {
res.redirect("/");
} else {
console.log(err);
}
});
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/compose",
failureRedirect: "/invaliduser",
session: true,
})
);
//the POST handler for processing the uploaded file
const port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function () {
console.log("Server started on port 3000");
});
请注意,只有当我安装 formidable 并且没有 express-formidabl 时才会发生这种情况,该网站运行良好!
I installed express-formidable and suddenly all of my post requests in the code stopped working. even i make a request, nothing happens. i tried it again by uninstalling express-formidable and it worked fine. what might be the problem?
heres my code,
const express = require("express");
const bodyParser = require("body-parser");
const mailchimp = require("@mailchimp/mailchimp_marketing");
const ejs = require("ejs");
const _ = require("lodash");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const { request } = require("express");
require("dotenv/config");
var formidable = require("express-formidable");
var eventsData = require("./events.json");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(formidable());
app.use(express.static("public"));
app.set("view engine", "ejs");
mailchimp.setConfig({
apiKey: process.env.MAILCHIMP_API,
server: process.env.MAILCHIMP_SERVER,
});
app.use(
session({
secret: "SLIITMOZILLA2022",
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(
process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
console.log("connected");
}
);
const blogSchema = new mongoose.Schema({
title: String,
content: String,
url: String,
image: String,
});
const eventSchema = new mongoose.Schema({
title: String,
description: String,
date: Date,
location: String,
img: String,
url: String,
});
const userSchema = new mongoose.Schema({
username: String,
googleId: String,
});
userSchema.plugin(passportLocalMongoose);
Blog = new mongoose.model("Blog", blogSchema);
Event = new mongoose.model("Event", eventSchema);
User = new mongoose.model("User", userSchema);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/compose", //ONLY FOR LOCAL USE
// callbackURL: "https://sliitmcc.herokuapp.com/auth/google/compose",
},
function (accessToken, refreshToken, email, done) {
User.findOne(
{ googleId: email.id, username: email.emails[0].value },
function (err, user) {
if (err) {
return done(err);
}
//No user was found... so create a new user with values from Facebook (all the profile. stuff)
else {
//found user. Return
return done(err, user);
}
}
);
}
)
);
app.get("/", (req, res) => {
Blog.find(
{},
{
_id: 0,
},
{ sort: { _id: -1 } },
function (err, items) {
res.render("index", { blog: items });
}
);
});
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["email", "profile"] })
);
app.get(
"/auth/google/compose",
passport.authenticate("google", { failureRedirect: "/login" }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/compose");
}
);
app.get("/blogs", (req, res) => {
res.render("blogs");
});
app.get("/events", (req, res) => {
res.render("events", { eventData: eventsData });
});
app.get("/contact_us", (req, res) => {
res.render("contact_us");
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/invaliduser", (req, res) => {
res.render("invaliduser");
});
app.get("/compose", (req, res) => {
if (req.isAuthenticated()) {
res.render("compose");
} else {
res.redirect("/login");
}
});
app.post("/", (req, res) => {
const userEmail = req.body.email;
const listId = process.env.MAILCHIMP_LIST_ID;
const subscribingUser = {
email: userEmail,
};
console.log("post working");
async function run() {
try {
const response = await mailchimp.lists.addListMember(listId, {
email_address: subscribingUser.email,
status: "subscribed",
});
console.log(" Succesfully Subscribed!");
res.redirect("/");
} catch (err) {
res.render("failure");
console.log(err.status);
}
}
run();
});
app.post("/blogs", async function (req, res) {
var limit = 6;
var startFrom = parseInt(req.fields.startFrom);
Blog.find(
{},
{
_id: 0,
},
{ sort: { _id: -1 }, skip: startFrom, limit: limit },
function (err, items) {
res.json({ blog: items });
}
);
});
app.post("/compose", (req, res) => {
const post = new Blog({
title: _.capitalize(req.body.title),
content: _.capitalize(req.body.content),
url: req.body.url,
image: req.body.image,
});
post.save((err) => {
if (!err) {
res.redirect("/");
} else {
console.log(err);
}
});
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/compose",
failureRedirect: "/invaliduser",
session: true,
})
);
//the POST handler for processing the uploaded file
const port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, function () {
console.log("Server started on port 3000");
});
Note this only happens when i install formidable and without express-formidabl, the website works well!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将属性 enctype="multipart/form-data" 添加到 login.ejs 文件中的表单标记中。
Add attribute enctype="multipart/form-data" to form tag in your login.ejs file.
好吧,我找到了一种通过 multipart/form 数据和 application/json 发送请求而不破坏任何东西的方法。
我实际上花了 2 个小时试图弄清楚发生了什么以及如何解决问题。
我发现“express-formidable”包不再维护并已被关闭。
然后我还发现了另一个包,它当然解决了现在的问题“express-formidable-v2”,我相信它是前一个包的延续。
检查这个 https://github.com/Abderrahman-byte/express-formidable-v2< /a> out,它是“express-formidable”包的一个分支
现在您可以访问您的 {req.fields} 和 {req.body}
Okay I found a way to send requests through the multipart/form data and the application/json without breaking any thing.
I actually spent 2 hours trying to figure out what happened and how to solve the problem.
I discovered that the package "express-formidable" is no longer being maintained and has been closed down.
Then I also found another package which of course solved the problem just about now "express-formidable-v2" which I believe is the continuation of the former package.
Check this https://github.com/Abderrahman-byte/express-formidable-v2 out, It is a fork of "express-formidable" package
Now you have access to your {req.fields} and {req.body}