hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.
Related
Im struggling to create API call to my database from node.js.
i have a postgres instance on Centos with multiple databases and table.
im trying to get table name "test_reslts" from database "sizing_results".
when the url, its just the server ip and port like http://{SERVER IP}:3300/
this is output -
"Cannot GET /"
when adding the table name or db name and table name, the request isn't completed and not output.
my code -
db_connection
const {Client} = require('pg')
const client = new Client({
user: 'postgres',
database: 'sizing_results',
password: 'password',
port: 5432,
host: 'localhost',
})
module.exports = client
api.js
const client = require('./db_connection.js')
const express = require('express'); // To make API calls
const app = express();
app.listen(3300, ()=>{
console.log("Server is now listening at port 3300");
})
client.connect();
app.get('/test_results', (req, res)=>{
client.query(`select * from test_results`, (err, result)=>{
if(!err){
res.send('BLABLA')
res.send(result.rows);
}
});
client.end;
})
Base on your answer to my comment I think it's not a DB connection problem.
It seems to be link to your routing, because it seems node never reach the inside of your route.
Are you sure you are calling the good route (http://localhost:3300/test_results) with no typo ? And with the good protocol (GET) ?
Hello totally awesome cool beautiful people! I am trying to get this custom middleware function to run upon an error. I am using express and I have a custom middleware function which should run when a new error is thrown.
All of this is written in express. I have read the docs and am still struggling to get this correct. Here is the middleware function.
const errorHandler = (err, req, res, next) => {
console.log("running error handler middleware")
const statusCode = res.statusCode ? res.statusCode : 500
res.status(statusCode)
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack
})
}
module.exports = errorHandler
Here is my entry point
const express = require('express')
const dotenv = require('dotenv').config()
const colors = require('colors')
const errorHandler = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const port = process.env.PORT || 5000
const app = express()
connectDB()
//these lines of middleware allow us to grab info from the req.body
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use('/api/goals', require('./routes/goalRoutes'))
app.use('/api/users', require('./routes/userRoutes'))
//pulling in our error handler middleware
app.use(errorHandler)
app.listen(port, () => {
console.log(`Server started on port ${port}`)
})
I have confirmed my file structure is correct and I am pulling the middleware in from the correct location. I have also made sure to place my app.use(errorHandler) at the bottom of my code to ensure it is the last error handler to run.
As of now when I encounter an error, my application crashed completely and does not return a json response with a stack trace.
This is going to cause issues later when trying to send errors back to the client side.
I can always go back to manually defining them through res.status(statusCode).json({message}) but this is the "node" way of doing things and does not implement the express syntax of "throw new Error(message)"
Any ideas on how to get a json response out of this without the app crashing while still using custom error handling and express throw new Error?
Thank you so much for the time, I appreciate it!
I'm using both Ubuntu and Visual Studio Code to launch my server program, they were both sucessfully taking and sending back replies from Postman a few days ago. The server code runs fine, and says the server is up and running at https://loccalhost:8080
But when I try to send a GET request from Postman, I get this error from Postman:
This is the environment I'm using:
And this is the error I get from my server program when it gets a request:
How ther server is configured:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("port", 8080);
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
const Pool = require("pg").Pool;
const config = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: "taskfour"
};
const pool = new Pool(config);
//HELLO WORLD
app.get("/hello", (req, res) => {
res.json({msg: "Hello, World!"});
});
app.listen(app.get("port"), () => {
console.log(`Find the server at http://localhost:${app.get("port")}`);
});
The server had previously been working fine, Postman was sending requests, doing tests, and my code was passing them. I didn't change much in the meanwhile, I'm not sure what changed. I've tried turning off my proxy server on Postman, but it hasnt' helped. Any help would be greatly appreciated.
Looks like the HTTP listening code is missing, for example:
app.listen(8080, function () {
console.log('App listening on port 8080.');
});
Wow, I didn't realize the postgres service wasn't running. I just needed to enter the command "sudo service postgresql start" in my terminal, and the requests work again.
Sorry for this noob question, student here and still learning
I'm trying to pass the request body of a POST request from server to client. I have an Arduino sensor making post requests with sensor data to an express server. The sensor data is inside the POST request body, and I push the data to an array called 'dataArray'. This part seems to be working.
My problem is that I'm now stuck on how to pass this data from the express server to a Vue component on the client side. Should I make a new route? I'm not asking anyone to write any code for me, I'm just hoping someone could point me in the right direction or suggest something, because I'm at a loss on exactly how I should go about doing this. Thank you.
server.js
var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
var Users = require("./routes/Users")
var port = process.env.PORT || 5000
var dataArray = []
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))
const mongoURI = 'my_connection_string'
mongoose.connect(mongoURI, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err))
app.use("/users", Users)
app.route("/api/:apikey1")
app.post("/api/:apikey1", function(request, response) {
var myData = request.body;
console.log(myData)
dataArray.push(myData)
response.send("Array Filled")
});
app.listen(port, function () {
console.log("Server is running on port: " + port)
})
If you want to keep it simple use the socket.io library.
It is available for both client and server, you can use in your Vue client too.
Also, you won't need any extra route, just in your app.post("/api/:apikey1") route, use the emit method on socket.io library to broadcast the data as it is received from the sensors
Any data flow from the server to client must be first initiated on the client side, either by polling, using WebSockets or Server-sent events.
I am working on an exercise tracker app using the MERN stack. I have a react JS component that is meant to allow me to add a new user to a database after I press the submit button. I am using axios to send http requests from my front end to server endpoint on the backend. However I keep getting this error
POST https://localhost:5000/users/add net::ERR_CONNECTION_REFUSED
Uncaught (in promise) Error: Network Error at createError
(0.chunk.js:971) at XMLHttpRequest.handleError (0.chunk.js:466)
This is my server side code
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
//mongoose is whats going to help us connect to our mongoDB database
require('dotenv').config();
//this configures si we can have our environment variables in the dotenv file
const app = express();
const port = process.env.PORT || 5000;
//this is how we will create our express server
app.use(cors());
app.use(express.json());
//this is our middle ware this will allopw us to parse json
// cause the server will be sending s=and receiving json
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology:true});
//uri is where database is stored
const connection = mongoose.connection;
connection.once('open',() =>{
console.log("MongoDB database connection established successfully");
});
//once connection is open its going to log the message
const exercisesRouter = require('./routes/excercises');
const usersRouter = require('./routes/users');
//importing
app.use('/excercises',exercisesRouter);
app.use('/users',usersRouter);
//use files
//whenever somebody goes to route url and put /excersies at the end it will show
//everything in excercises and the same for users
app.listen(port,()=>{
console.log('Server is running on port: ' + port);
});
//this is what starts the server. It start listening to a certain port
This is my submit function
onSubmit(e){
e.preventDefault(); //prevents default html form behaviour taking place
const user = {
username: this.state.username,
};
console.log(user);
//sending user data to the backend with post request
//check user.js file in routes its sending a post request to the user.add api
axios.post('https://localhost:5000/users/add',user)
.then(res => console.log(res.data));
this.setState({
username: ''
});
}
This is my route
router.route('/add').post((req,res) => {
const username = req.body.username;
const newUser = new User({username});
//using unsername to create new user
newUser.save()
.then(() => res.json('User added')) //after user saved to DB return user added message
.catch(err => res.status(400).json('Error ' + err)); //if there is an error return error
});
check if your backend is also running on port 5000 u need to start your backend
I followed this tutorial as well, you have to start the backend and the front end. The problem was the front end is only running that's why you can see everything( not sure how he managed ) but I had to pull up a terminal and start the front end with -> npm start and the backend with -> nodemon server on a separate terminal tab
bro, I think you did just a little mistake in your address which is
https://localhost:5000/users/add not https change it to http and it will solve your problem
your address will be http://localhost:5000/users/add