URL shortener microservice input URL problem

I am just trying to get started on this little project and I am stuck on just getting and printing out the input URL. I got deprecated messages when I tried to use body parser so I used what I’ve found elsewhere as what to use with the later express versions. My problem is that when I console log what I think should be the input URL that was passed as data with a POST I assume I just get ‘[object Object]’ printed out instead of a url. It prints out 3 times so I assume the challenge sends three post requests but not sure how to access the url itself in the post request. Not sure what I’m doing wrong . I wish they would give you an actual full post request that looks like what will be sent but in any event here is my code so far:

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

const dns = require('dns');

// Basic Configuration
const port = process.env.PORT || 3000;

app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

// URL Shortener microservice

app.use(express.json()); //For JSON requests
app.use(express.urlencoded({extended: true}));

var urls = {};
app.post('/api/shorturl/', (req, res) => {
  var origUrl = req.body;
  var shortUrl = "abc";
  console.log("original URL: "+origUrl);
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});

Your project link(s)

solution: https://replit.com/@cavasian/boilerplate-project-urlshortener

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge: URL Shortener Microservice

Link to the challenge:

Try:

  console.log(`req.body: ${JSON.stringify(req.body, null, 2)}`);

which prints

req.body: {
  "url": "https://boilerplate-project-urlshortener-20.jeremyagray.repl.co/?v=1645752001975"
}

Your code

should print original URL: [object Object] since that’s how JS will handle objects combined with strings and req and req.body are both objects and you didn’t explicitly stringify it. You could get one level of stringification if you had used console.log(req.body);, but JSON.stringify() will stringify to JSON as far as possible, as advertised.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.