我正在使用以下用户控制器通过Node Express和MongoDB插入用户。当我开始使用Postman Body表单数据插入值时,我得到以下输出为error_message“无效的请求,无效的'名称'参数。该错误表明我想在模式中插入名称字段的值,但是我在主体表单数据中输入名称字段及其值作为键和值,所以为什么这不起作用?
userController.js
const express=require("express");
const router =express.Router();
const mongoose=require("mongoose");
const multer = require('multer');
var assert = require('assert');
const User = require('../models/user.model.js');
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var bodyParser = require('body-parser');
var app = express(); // define our app using express
// Put these statements before you define any routes.
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
// POST
exports.create = ("/",(req, res, next) =>
{
var varName= req.body.name;
var varUname = req.body.username;
var varPass = req.body.password;
var varEmail = req.body.email;
if(!varName)
{
return res.status(400).send(
{
"error_message": "Invalid request, Invalid 'name' parameter.",
"status": "INVALID_REQUEST"
}
);
}
// Other Validations are go here...
const user = new User(
{
name: varName, //required
address: req.body.address,
logo: req.body.logo,
username: varUname, //required
password: varPass, //required
phone_number: req.body.phone_number,
email: varEmail, //required
token_key : token
});
// Save Programe in the database
user.save()
.then(data => {
res.send(
{
"error_message": [],
"results":"User created successfully",
"status": "Success",
"token": token
});
}).catch(err => {
res.status(500).send({
error_message: err.message || "Some error occurred while creating the Programe."
});
});
});
// GET all
exports.findAll = (req, res) =>
{
User.find()
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
error_message: err.message || "Some error occurred while retrieving programe."
});
});
};
已更新,请参阅我添加的server.js
代码
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
// Configuring the database
const dbConfig = require('./config/database.config.js');
var multer = require('multer');
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...');
process.exit();
});
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to Agenda APP created by ApptimusTECH."});
});
require('./app/routes/programe.routes.js')(app);
require('./app/routes/user.routes.js')(app);
require('./app/routes/agenda.routes.js')(app);
// listen for requests
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
答案 0 :(得分:0)
您可以使用此方法进行修复。请看看。
const path = require('path'),
fs = require('fs'),
util = require("util"),
formidable = require('formidable');
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
// `file` is the name of the <input> field of type `file`
console.log("line 98");
console.log(files);
console.log("line 100");
console.log(fields);
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
form.on('error', function(err) {
console.error(err);
});
form.on('progress', function(bytesReceived, bytesExpected) {
var percent_complete = (bytesReceived / bytesExpected) * 100;
console.log(percent_complete.toFixed(2));
});
form.on('end', function(fields, files) {
Temporary location of our uploaded file
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Location where we want to copy the uploaded file */
var new_location = '../client/public/media/tickets/';
fs.readFile(temp_path, function(err, data) {
fs.writeFile(new_location + file_name, data, function(err) {
fs.unlink(temp_path, function(err) {
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
});
});
});