Before embarking on the routes of my application, I have created some requests with POSTMAN of which PUT is not made to me in full.
This is my configuration of my server in ExpressJS:
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const mongoose = require('mongoose');
const app = express();
// Settings
app.set('port', process.env.PORT || 3000);
mongoose.connect('mongodb://localhost/mevn-curso', {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
app.use(helmet());
// Routes
app.use('/tasks/', require('./routes/tasks'));
// Static files
app.use(express.static(__dirname + '/public'))
app.listen(app.get('port'), ()=> {
console.log('Server on port', app.get('port'));
});
It works for me normally and this is the router I am using, which is inside the tasks.js file in the routes folder:
const express = require('express');
const router = express.Router();
const Task = require('../models/Task');
router.get('/', async (req,res)=> {
const tasks = await Task.find();
res.json(tasks);
})
router.post('/', async (req,res) => {
const task = new Task(req.body);
await task.save();
res.json({
status: "Task Saved"
})
})
router.put('/:id', async (req,res)=> {
console.log(req.params._id);
console.log(req.body);
await Task.findByIdAndUpdate(req.params._id, req.body)
res.json('recivied');
console.log('Listo')
})
module.exports = router;
In console does not seem to give me any error. I make the request with normal POSTMAN, and it returns the logs of the console. Even the server answers the json and everything. But the data in the database is not changed. This does not happen with GET or POST, on the contrary, everything is going well.
Here I leave you how I make the request with POSTMAN. First of all I am going to show you the data that I already have in the database, with the get request that is normally done with the browser:
ready, when I'm making the PUT request this is my configuration in POSTMAN:
It's a json type content type because that's what I'm going to process, then comes the body:
and this is the answer in the console:
What do you think it could be?
as I see the console.log of req.params._id is undefined: change the
Task.findByIdAndUpdate(req.params.id, req.body) changed _id to id
router.put('/:id', async (req,res)=> {
console.log(req.params.id);
console.log(req.body);
await Task.findByIdAndUpdate(req.params.id, req.body)
res.json('recieved');
})
Related
I am making a Web-Notepad using Nodejs and express where all the data is gonna be saved in MongoDB. I want to grab the data through my Rest API making an HTTP request with Axion.
When I send the GET request, the program doesn't wait for the JSON file, continues and because of that, it exports an undefined file with the site is getting shown without the data.
With the console.log after the GET request, I get all the data I need - but too late.
app.js:
const express = require('express');
const chalk = require('chalk');
const debug = require('debug')('app');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv/config')
const app = express();
const port = 3000;
app.use(cors());
app.use(express.static('views'));
app.use(bodyParser.json());
app.set('views', './views');
app.set('view engine', 'ejs');
const postsRoute = require('./routes/posts');
// Here i import the data from the GET request
const getData = require('./routes/router');
app.use('/posts', postsRoute);
// The outcome of this log is; Promise {<pending>}
console.log(getData);
app.get('/', (req, res) => {
res.render(
'index',
{
// Here i want to send the Data to the ejs file
getData,
title: 'Notepad'
});
});
// Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false}, () =>
debug('Connected correctly to MongoDB')
);
app.listen(port, () => {
debug(`Listening on port ${chalk.green(port)}`);
});
router.js where i make the GET request (i should change the name of the file...)
const axios = require('axios').default;
async function getData() {
try {
const response = await axios.get('http://localhost:3000/posts');
console.log(response);
return response.data
} catch (err) {
console.log(err);
}
}
module.exports = getData();
GET Request:
router.get('/', async (req, res) => {
try {
const posts = await post.find();
res.json(posts);
} catch (err) {
res.json({message: err})
}
});
I am encountering a problem when I try to make a post request with mogoose using the Postman, i get the following answer:
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /</pre>
</body>
</html>
I can't understand the reason, my index.js code:
const express = require("express");
const mongoose = require("mongoose");
const cors = require('cors')
const bodyParser = require('body-parser')
mongoose.connect(
process.env.MONGODB_URL || "mongodb://localhost/trading",
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
}
).then(item => {
console.log('conectado com o banco')
}).catch((err)=>{
console.log(err)
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
const candlesRoute = require("./routes/candles");
const home = require("./routes/home");
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE');
app.use(cors());
next();
})
app.use("/", home);
app.use("/candles", candlesRoute);
const PORT = 8080;
app.listen(PORT, () => {
console.log("Servidor Conectado");
});
my route candles.js :
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
require("../models/Candles");
const candlesTick = mongoose.model("candles");
router.post('/candles', async (req, res) => {
try {
const velas = req.body
await new candlesTick(velas).save();
console.log('successe')
} catch (error) {
console.log(error);
}
});
module.exports = router;
and finally my model Candles.js:
const mongoose = require('mongoose')
//const Schema = mongoose.Schema
const Candles = new mongoose.Schema({
titulo: {
type: String,
},
})
mongoose.model("candles", Candles);
my request in the Postman is as follows
{
"titulo": "DENT/ETH"
}
I have already tmbm send the data directly and even then it does not work, I do not understand the reason for this, please if anyone can help thanks
app.use("/candles", candlesRoute); will add namespace to that route and router also has candles in the post request. At the end the available route will be POST {{host}}/candles/candles.
Please try remove candles from
router.post('/candles', async (req, res) => {
...
})
or have the URL in postman as {{host}}/candles/candles
I think req.body is not parsed, because you've set bodyparser extendedUrl to false. Try this:
app.use(bodyParser.urlencoded({extended: true}))
Also you simply create your object with MyModel.create(myContent) instead of using new Model() + save().
you should have posted your terminal logs also but nvm :)
I can guess the problem by looking at your code : -
Your mongodb local URL is wrong there is no mention of port.
it is always like mongodb://localhost:27017/trading for local server
I have less idea about this but you didn't export model in Candles.js
I am new at web development and saying sorry for this question. THE thing is that i have done a serverside with Express and connected to MongoDB, have already established the connection where i can insert, select, delete information, but don't know how to make Frontend side with NUXT.JS, i want to put 4 buttons in frontend which will be select, insert, delete buttons . Here is my backend:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});
// Require Notes routes
require('./app/routes/note.routes.js')(app);
// listen for requests
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
I am using express 4.
in my server.js I have express.json() middleware
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const errorHandler = require('./_helpers/error-handler');
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json()); /////////////////////////////////////////
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
});
// routers
app.use('/api/users', require('./routes/api/users/users.controller'));
app.use('/api/orders', require('./routes/api/orders/orders.controller'));
app.use('/shopify/app', require('./routes/shopify/app/shopify.controller'));
app.use('/shopify/app/webhooks', require('./routes/shopify/app/webhooks/webhooks.controller')); ///////////////
app.use(errorHandler);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
but for '/shopify/app/webhooks' route I need to get raw body so I can create hash
but so far I am receiving Object because I have express.json() middleware.
this is my webhooks.controller.js file
const express = require('express');
const router = express.Router();
const crypto = require('crypto')
const SHOPIFY_API_SECRET_KEY = process.env.SHOPIFY_API_SECRET_KEY;
// router.use(express.raw({ type: "application/json"}));
// routes goes here
router.post('/app/uninstalled', express.raw({ type: 'application/json' }), async (req, res, next) => {
const hmac = req.get('X-Shopify-Hmac-Sha256')
console.log(req.body);
// create a hash using the body and our key
const hash = crypto
.createHmac('sha256', SHOPIFY_API_SECRET_KEY)
.update(req.body, 'utf8', 'hex')
.digest('base64')
// Compare our hash to Shopify's hash
if (hash === hmac) {
// It's a match! All good
console.log('Phew, it came from Shopifify!')
res.sendStatus(200)
} else {
// No match! This request didn't originate from Shopify
console.log('Danger! Not from Shopify!')
res.sendStatus(403)
}
})
what I have tried is in webhooks.controller.js router.use(express.raw({type: "application/json"}))
i thought since I am receiving json object I can use express.raw() middleware that accepts json
but it's still not working.
You have to place this route BEFORE your app.use(express.json()) middleware and then you can apply the raw middleware directly to that route:
app.use('/shopify/app/webhooks', express.raw({/* put your options here */}), require('./routes/shopify/app/webhooks/webhooks.controller'));
Keep in mind that this line of code must go physically before your express.json() middleware.
We can get useful info for specific routes before applying body parser.
So, if you want to get raw body for stripe webhooks.
We can do like this.
app.use(bodyParser.json({
extended: true,
verify: function (req, res, buf) {
if (req.originalUrl.endsWith('/stripe/webhooks')) {
req.rawBody = buf
}
}
}))
I'm making a POST request from a React front-end using axios to an endpoint to save some data to my DB (MongoDB). I'm getting an error that one cannot read property 'name' of undefined. I think that's occurring because req.body is undefined but I can't understand what's wrong with my axios request. I logged all the parameters and they are there (not undefined). The axios request and the endpoint are written below. Any help will be appreciated. Thanks!
Axios Request
const uploadElement = async (name, HTMLCode, JSCode, CSSCode, screenshot) => {
console.log(name)
try {
await axios({
method: 'post',
url: '/api/elements',
data: {
name: name,
HTMLCode,
JSCode,
CSSCode,
screenshot
}
});
} catch (e) {
console.log(e);
}
}
Endpoint for POST Request
router.post("/", upload.single("screenshot"), async (req, res) => {
try {
const newElement = new Element({
name: req.body.name,
JSCode: req.body.JSCode,
HTMLCode: req.body.HTMLCode,
CSSCode: req.body.CSSCode,
screenshot: req.file.buffer,
});
await newElement.save();
res.send("Data uploaded successfully!");
} catch (e) {
console.error(e);
}
});
Server.js
const express = require("express");
const passport = require("passport");
const session = require("express-session");
const cors = require('cors');
const elementRouter = require("./routes/elementRoute");
const authRouter = require("./routes/authRoute");
const connectDB = require("./config/db");
const app = express();
const port = process.env.PORT || 5000;
connectDB();
app.use(
session({
secret: "googleOAuth",
resave: false,
saveUninitialized: true,
})
);
app.use(cors());
// Passport Config
require("./config/passport")(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use("/api/elements", elementRouter);
app.use("/api/auth", authRouter);
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
You need to install and require body-parser in your serverside code
First run npm i --save body-parser
Then require it like this
const bodyParser = require("body-parser");
Then use it after you declare your app ( after this line const app = express();)
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
This makes the data of your request available in req.body