SK1dev
SK1dev

Reputation: 1139

receive 404 error from post request: postman

I am trying to make a post request from postman but I'm receiving a 404 error: SyntaxError: Unexpected token n in JSON at position 4<br> &nbsp; &nbsp;at JSON.parse. I have added the Content-Type: application/json header and defined the json body in the raw tab. This is the url: http://localhost:8000/api/signup. I can't make this post request nor can I access the application in the browser as I receive cannot GET /api/signup.

enter image description here

How can I fix this?

controllers/user.js

const User = require('../models/user')
const { errorHandler } = require("../helpers/dbErrorHandler")

exports.signup = (req, res) => {
    console.log("req.body", req.body)
    // signs up new user
 const user = new User(req.body)
 user.save((err, user) => {
if(err) {
    return res.status(400).json({
        err: errorHandler(err)
    })
}
res.json({
    user 
 })
 })
}

app.js

const express = require('express')
const mongoose = require('mongoose')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')

require('dotenv').config()

// import routes
const userRoutes = require('./routes/user')

// app
const app = express()

// connect db - first arg is url (specified in .env)
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
}).then(() => console.log('DB connected'))

// middlewares 
app.use(morgan('dev'))
app.use(bodyParser.json())
// used to save users credentials
app.use(cookieParser())


// routes middleware
app.use('/api', userRoutes)

const port = process.env.PORT || 8000

app.listen(port, () => {
    console.log(`Server is running on port ${port}`)
})

models/user.js

const mongoose = require('mongoose')
const crypto = require('crypto')
const uuidv1 = require('uuid/v1')

const userSchema = new mongoose.Schema ({
...
}, {timestamps: true})



userSchema.methods = {
    encryptPassword: function(password) {
        if (!password) return '';
        // hashes password
        try {
            return crypto.createHmac('sha1', this.salt)
            .update(password)
            .digest('hex')
        } catch (err) {
            return ''
        }
    }
}

module.exports = mongoose.model("User", userSchema)

routes/user.js

const express = require('express')
const router = express.Router()

const { signup} = require('../controllers/user')

router.post('/signup', signup)

module.exports = router

Upvotes: 0

Views: 26055

Answers (3)

Kong
Kong

Reputation: 301

This seems like two different issues, for the POST request, the error seems like there is an invalid string in your JSON payload that your application cannot read and parse.

The second one is mainly due to the route is not found, without looking at your ./routes/user file, it seems like there are two possibilities:

  1. You have a nested route of /user/.... If that is the case, try accessing your api via /api/user/signup instead of /api/signup
  2. You did not create a GET route for you signup path. Normally signup is a POST path instead of GET.

It would be best if you can provide the source code of ./routes/user.js for us to properly answer this.

Upvotes: 1

Harshal Yeole
Harshal Yeole

Reputation: 5003

404 means NOT Found,

May be your URL or Method is wrong

Here is what you can try to diagnose:

  1. Check if server is running
  2. Check the port and URL you are accessing.
  3. Check the postman method POST and URL.
  4. Check the route, routes file and match it with postman URL

Upvotes: 1

Sourav Dey
Sourav Dey

Reputation: 1160

404 error is an HTTP status code that means that the page you were trying to reach on a website couldn't be found on their server. To be clear, the 404 error indicates that while the server itself is reachable, the specific page showing the error is not.

Make sure that your indexing is correct and your local server is running properly.

Upvotes: 0

Related Questions