Home > Net >  getting error 405 'Method not Allowed' When trying to send request to my node server
getting error 405 'Method not Allowed' When trying to send request to my node server

Time:03-08

Its my first time using Express and MongoDB, i have created my Node server and connected it to my mongoDB database, but when i try to send an request from my html page to the server i get Error 405 method not allowed, following is my node.js server code

mongoose.connect('mongodb://localhost/userdatabase' ,{
    useNewUrlParser: true,
    useUnifiedTopology: true
})
const app = express()
app.use('/', express.static(path.join(__dirname, 'static')))
app.use(bodyParser.json())

const port = 5500

app.listen(port, () => {
    console.log(`server is up at ${port}`)
})
   
app.post('/api/register', async(req, res) => {
const {username, password} = req.body
res.json({status: 'ok'})
try{
    const response = await User.create({
        username,
        password
    })
    console.log('User created succesfully' , response)
}catch(error){
    console.log(error)
}
})

and here is the function im trying to call to do the post request

  const form = document.querySelector('#register')
form.addEventListener('submit', registerUser)

async function registerUser(event){
  event.preventDefault()
  const username = document.getElementById('username').value
  const password = document.getElementById('password').value

const result = await fetch('/api/register', {
    method: 'POST',
    headers: {
      'Content-Type' : 'application/json'
    }, body: JSON.stringify({
      username,
      password
    })
  }).then(res => res.json())
}

basically i am creating an login system and try to register users, but for some reason i keep getting the error 405 when trying to call the Server, Note that for some reason it worked 3 times when i was trying earlier, I havent changed almost anything in the code but it just wont work, what it can be ? thanks in advance

CodePudding user response:

You should tell in which port mongoDB would run.

const mongoose = require('mongoose');

main().catch(err => console.log(err));

async function main() {
  await mongoose.connect('mongodb://localhost:27017/test');
}

CodePudding user response:

I think you have to declare the server and port while calling the axios. The axios call should be - await fetch('localhost:5500/api/register'). It's searching for '/api/register' but didn't find anything. Hope this will solve your issue.

  • Related