1

I have been working on a project for a url shortener, where I am trying to increment views every time someone hit that api or someone make a get request. I don't know what is getting wrong but the views are just incrementing for once only.

enter image description here

Here's the code I wrote to increment the views every time a get request is made.

  • Get - link
  • Incrementing in mongodb - link

I do not know what is going wrong, I have already searched through lot of forums, stack overflow, articles already asked problems.

Note -

  • The default value of views is 0 , here is the value in post request.
  • Distinct users, generated by are dummy values as of now.
  • Mongoose Schema Link - link
  • I am creating this project with nodejs, expressjs, mongodb(database), mongoose(orm), pugjs(view engine).
  • Project Link : link

Here's the file tree

├── LICENSE
├── README.md
├── client
│   ├── assets
│   │   ├── bg.svg
│   │   ├── favicon
│   │   │   └── favicon.ico
│   │   └── fonts
│   │       ├── Apercu\ Medium.woff
│   │       ├── Apercu\ Mono.woff
│   │       └── Apercu_Regular.woff
│   ├── css
│   │   └── style.css
│   ├── index.html
│   └── js
│       └── script.js
├── index.js
├── models
│   ├── admin_model.js
│   └── urlshorten.js
├── package-lock.json
├── package.json
├── routes
│   ├── admin.js
│   ├── auth.js
│   ├── custom.js
│   ├── stats.js
│   └── urlShorten.js
├── static
│   ├── css
│   │   └── style.css
│   ├── favicon.ico
│   ├── fonts
│   │   └── Inter-Regular.woff
│   └── urlshort.gif
└── views
    ├── index.pug
    └── script.js
Raghav Sharma
  • 141
  • 2
  • 13

1 Answers1

3

In simple terms:

1. It is because of 301 Status Code for Redirect you are using.
2. 301 Status Code represents a Permanent Redirect.
3. The browser stores the main URL in the memory.
4. The next time you request the short link from your browser, it gets the Original
   URL from its memory and sends you there, without going through the Server.
5. Since the request doesn't go through the server, the server fails to increment it.

Solution:

Change 301 (Permanent) Status code to 307 (Temporary) Status Code.

FILE: ShortLink/routes/urlShortner.js

Change the below lines

Line 37:  res.writeHead(301, {
Line 38:      Location: url.inputUrl
Line 39:  });

to

Line 37:  res.writeHead(307, {
Line 38:      Location: url.inputUrl
Line 39:  });

I have also created a pull request to your Github Repo which you can verify.

Anteraez
  • 86
  • 3
  • 1
    It worked! @Anteraez, I was stuck on this since a long time! Kudos! :) – Raghav Sharma Oct 17 '19 at 09:52
  • @RaghavSharma It was my pleasure. Here's a good resource to learn more about HTTP Status Codes. [MDN HTTP Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) – Anteraez Oct 17 '19 at 10:12