My POST method is not working, while my GET function is. What am I doing wrong?

57 views Asked by At

I am building an URL shortener using Node.js, express and Monk. But I keep getting an error when trying to POST.

I am trying to post data to my mongo database, but I keep getting 500 error. What am I doing wrong here? When I am trying to read, so the app.get('/:name') function from index.js, it works. So I know the connection is working.

This is my index.js

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');

const urls = require('./db/urls');

const app = express();

app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public'))

app.get('/:name', async (req, res) => {
  const short = await urls.find(req.params.name);
  if (short) {
    res.redirect(short.url);
  } else { 
    //res.redirect(`/404.html?name=${req.params.name}`);
  }
});

app.post('/api/short', async (req, res) => {
  console.log(req.body);
  try {
    const url = await urls.create(req.body);
    res.json(url);
  } catch (error) {
    res.status(500);
    res.json(error);
  }
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
})

This is my database

const monk = require('monk');
const connectionURL = process.env.MONGODB_URI || 'localhost/url-shortener';

const db = monk(connectionURL);

module.exports = db;
const Joi = require('@hapi/joi')
const db = require('./connection');

const urls = db.get('urls');

const schema = Joi.object().keys({
  name: Joi.string().token().min(1).max(100).required(),
  url: Joi.string().uri({
    scheme: [
      /https?/
    ]
  }).required()
}).with('name', 'url');

function find(name) {
  return urls.findOne({
    name
  });
}

async function create(shortURLInfo) {
  const result = Joi.validate(shortURLInfo, schema);
  if (result.error === null) {
    const url = await urls.findOne({
      name: shortURLInfo.name
    });
    if (!url) {
      return urls.insert(shortURLInfo);
    } else {
      return Promise.reject({
        isJoi: true,
        details: [{
          message: 'Short name is in use.'
        }]
      });
    }
  } else {
    return Promise.reject(result.error);
  }
}

module.exports = {
  create,
  find
};

And this is my function that calls the database

new Vue({
  el: '#app',
  data: {
    name: '',
    url: ''
  },
  methods: {
    createShortURL() {
      const body = {
        name: this.name,
        url: this.url
      };

      fetch('/api/short', {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
          'content-type': 'application/json'
        }
      }).then(response => {
        return response.json();
      }).then(result => {
        console.log(result);
      })
    }
  }
});
0

There are 0 answers