【问题标题】:MongoDB value not incrementing after incremented onceMongoDB值在增加一次后不增加
【发布时间】:2020-02-14 02:54:46
【问题描述】:

我一直在做一个 url 缩短器的项目,我试图在每次有人点击该 api 或有人发出 get 请求时增加 views。我不知道出了什么问题,但视图只是增加了一次。

这是我编写的代码,用于在每次发出 get 请求时增加视图。

  • 获取 - link
  • 在 mongodb 中递增 - link

我不知道怎么回事,我已经搜索了很多论坛,stack overflowarticles已经问过问题了。

注意 -

  • views的默认值为0herepost请求中的值。
  • 截至目前,生成的不同用户是虚拟值。
  • Mongoose 架构链接 - link
  • 我正在使用 nodejs、expressjs、mongodb(database)、mongoose(orm)、pugjs(view engine) 创建这个项目。
  • 项目链接:link

这是文件树

├── 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

【问题讨论】:

    标签: node.js mongodb express mongoose backend


    【解决方案1】:

    简单来说:

    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.
    

    解决方案:

    将 301(永久)状态代码更改为 307(临时)状态代码。

    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:  });
    

    我还向你的 Github 存储库创建了一个拉取请求,你可以验证它。

    【讨论】:

    • 成功了! @Anteraez,我很长时间以来一直坚持这一点!赞! :)
    • @RaghavSharma 这是我的荣幸。这是了解有关 HTTP 状态代码的更多信息的好资源。 MDN HTTP Status Codes
    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多