I sent a request from postman in nodejs and as a beginner in nodejs i find it hard to debug .Can someone throw light on this ?
Here is the entire repository at this point of time .
https://github.com/kolaveridi/socialnetwork
router.get('/handle/:handle', (req, res) => {
console.log('working');
console.log(req.params.handle);
const errors = {};
Profile.findOne({ handle: req.params.handle })
.populate('user', ['name', 'avatar'])
.then(profile => {
if (!profile) {
errors.noprofile = 'There is no profile for this user';
console.log('no profile');
res.status(404).json(errors);
}
res.json(profile);
})
.catch(err => res.status(404).json(err));
});
I don't see any of the console working on sending this request
when i already have a user with handle 'mom' regsitered ,loggedin .
http://localhost:5000/api/profile/handle/:mom
The problem is not in the source code itself, but in the api url you use to test the app. ":" is only needed in the "handle" route declaration, but in the url you need to skip it:
http://localhost:5000/api/profile/handle/mom
Regarding the question: you can use console.log and build in debugger (node inspect server.js), or you can use IDE debugger.
Related
I am not sure what is happening. I had all the same code setup in dev using localhost and everything was working fine. I hosted my app to Vercel and my API to heroku and from what I can tell the API is working perfectly. The issue now is when I make a post request I get a 400 Bad Request error in the browser but it still makes the request and posts to my DB I have setup. Any help can be appreciated. I built this application in a MERN stack with NEXT.js
Here is my client side Post request
const postSubmit = async e => {
e.preventDefault();
try {
const { data } = await axios.post('/create-post', { content, image });
if(data.error) {
toast.error(data.error);
} else {
setPage(1);
newsFeed();
toast.success("Post created");
setContent('');
setImage({});
// socket.emit('new-post', data);
}
} catch(e) {
console.log(e);
}
}
Here is my server side handling of the post request
export const createPost = async (req, res) => {
const { content, image } = req.body;
if(!content.length) {
return res.json({
error: 'Content is required'
})
}
try {
const post = new Post({ content, image, postedBy: req.user._id });
await post.save();
const postWithUser = await Post.findById(post._id).populate('postedBy', '-password -secret');
res.json(postWithUser);
} catch (e) {
console.log(e);
res.sendStatus(400);
}
};
And here is what the browser is telling me
Chrome Browser Info
This is most likely caused by a typo on the MongoDB connection string (URI), similar to this answer.
In the linked answer, the typo was the semi-colon in &w=majority;. In your case, the value is somehow majorityDATABASE=, so double-check your MongoDB connection string and try to remove the extra DATABASE= in the write concern parameter.
It's likely that the await Post.findById() call is not finding a result which could be throwing an error when you try to call res.json(postWihUser). That would then cause an error when postWithUser is not defined.
What is logged to the server's terminal when an error occurs? That should help you identify the problem.
I am kind of stuck at something, I am working on a personal blog that is full stack using mongodb with node.js and express. In that blog website only one user can sign up, and all posts are connected to that user. I am using the REST API to create a controller that deletes a user along with all the posts. I have the User and the Post object available and I was wondering if there is a way where I can use the User and Post schema objects to delete the user and ALL posts. I dont want to use the db.collection('posts') thing because I havent used that anywhere else. I went through mongodb node.js driver docs and I still cant figure out how to do it.
exports.deleteUser = (req, res, next) => {
User.find().then(user => {
//what do i do here?
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// you need to do next() otherwise error will not reach
// our middlewear in app.js file
next(err);
})
Post.find().then(allPosts => {
if (!allPosts) {
//what do i do here?
}
res.status(200).json({message: message})
})
.catch(err => {
if (!err.statusCode) {
err.statusCode = 500;
}
// you need to do next() otherwise error will not reach
// our middlewear in app.js file
next(err);
})
}
I would recommend using deleteOne and deleteMany directly instead of using find.
I am using Knex JS for user authentication in order to get email and password from the user and connect to PostgreSQL to check for authentication.
router.post('/login', async (req, res) => {
knex.select('email','password').from('users')
.where('email', '=',req.body.email)
.then((data) => {
const isValid = bcrypt.compareSync(req.body.password, data[0].password);
if (isValid === true) {
res.render('index-v1');
}
});
});
But the render function is not rendering the index ejs file but rather the localhost is not responding.
Thanks in advance for the help.
So, as the comments suggest, there are two possible paths not covered by your route, which is apparently leading to a lack of response from the server. Remember, if you don't tell it to respond (with res.render or similar) it won't respond, leaving your client hanging.
router.post('/login', async (req, res) => {
try {
const data = await knex.select('email', 'password')
.from('users')
.where('email', '=', req.body.email)
const isValid = bcrypt.compareSync(req.body.password, data[0].password);
if (isValid) {
res.render('index-v1');
return
}
res.render('error-page');
} catch (e) {
res.render('error-page');
}
});
In other words: if the password is incorrect, we still need to respond to the client. If there's some kind of database error (or the user doesn't exist, say) we still need to respond to the client. Exactly how you respond is of course up to you, but that's the kind of structure you need to think about.
I'm trying to test an endpoint that should receive a multipart/form-data. I'm sending a collection of images, which i want to process and save on the server or CDN. I'm using Jest, Express and Formidable.
Endpoint
router.post("/videos", async (req, res) => {
new formidable.IncomingForm().parse(req, (err, fields, files) => {
console.log('PARSE FORM');
if (err) {
console.error('Error', err);
throw err
}
console.log('Fields', fields);
console.log('Files', files);
for (const file of Object.entries(files)) {
console.log('FILE', file)
}
});
res.status(200).send('Created Video');
});
Test
describe("Video Endpoints", () => {
it('should create a new timelapse video', done => {
request
.post('/api/videos')
.field('file', 'some random value')
.attach('image', `${__dirname}/__mocks__/image.png`)
.then(res => {
console.log('THEN');
done();
})
});
});
When running the test it doesn't reach the formidable parse method.
If change my my attach method to this...
.attach('image', fs.readFileSync(`${__dirname}/__mocks__/xdebugcurlaccessingwpapi.png`))
It will reach the parse method but it sees the it as field and not a file.
If i make the same request but from my react app using fetch, it works perfectly fine.
What am i doing wrong? Been on this for a few days now lol.
Any help would be great.
Thanks.
I'm not entirely sure why but if you add
.set({connection: 'keep-alive'})
Then it works.
Final solution
request
.post('/api/videos')
.set({connection: 'keep-alive'})
.field('name', 'Richard')
.attach('image', mockImage)
.then(res => {
console.log('THEN');
done();
});
});
Would be good if someone has an understanding to why this is the case.
I think it might close the stream to image but can't be sure.
In trying to build my first express API, I am encountering many problems. I am following some simple guide on youtube, and his code works (FOR HIM). When I try it with Postman, I simply get nothing, but it appears to be in some kind of loop (because I handle the errors)
I have checked that my route is ok, and tried experimenting with next() (which seems like I don't need it just yet)
Player is my model made with Mongoose
app.get("/players/:id", (req, res) => {
const id = req.params.id;
Player.findById(id)
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json(doc);
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
So when trying a GET in Postman on:
http://localhost:3000/players/5cf66338f00c424494316eb2
I get a loading screen, and after some time "There was an error connecting to...".
Any help/tips/solution/insights are appreciated!
If your repo is up-to-date, then you are not connecting your app with your database.
Add the following code in your app replacing the database with your own database:
mongoose.connect('mongodb://localhost:27017/database', {useNewUrlParser: true});