首页 \ 问答 \ 为什么我必须在mongoDB查询中使用+(Why must I use + in mongoDB query)

为什么我必须在mongoDB查询中使用+(Why must I use + in mongoDB query)

我正在做Learnnyoumongo教程来学习mongoDB。

在第三个练习( 找到教程),直到我找到解决方案,我才能让它工作。 我的错误是查询在参数前面需要一个“+”。

所以db.coll.find({ $gt: process.argv[2] })不起作用,但{ $gt: +process.argv[2] }没有。

也许这是一个愚蠢的问题,但是什么是加号,我何时会使用它?

它也在常规javascript中发挥作用吗?


I am doing the learnyoumongo tutorials to learn mongoDB.

On the third excercise (the find tutorial) I couldn't get it to work until i just found the solution. My mistake was that the query needed a "+" in front of the argument.

so db.coll.find({ $gt: process.argv[2] }) did not work, but { $gt: +process.argv[2] } did.

Perhaps this is a stupid question, but what is that plus sign, and when would I use it?

Also does it play a role in regular javascript?


原文:https://stackoverflow.com/questions/31528062
更新时间:2022-12-04 16:12

最满意答案

这是angular2-jwt的默认行为

默认情况下,如果没有保存有效的JWTAuthHttp将返回带有“无效JWT”的Observable错误 。 如果您希望继续使用未经身份验证的请求,则可以将noJwtError设置为true

您只应在要进行经过身份验证的请求时使用AuthHttp ,因此在您的AuthService上还需要导入Http服务,如下所示:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp } from "angular2-jwt";

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        });
    }
}

如前所述,在Angular2-jwt检查有效的JWT令牌之前,如果有任何机会没有有效的JWT,那么它甚至不会执行请求。

但是如果你想为每个请求使用authHttp你可以通过覆盖提供者的配置来禁用JWT令牌验证,在app.modute.ts上添加如下:

import {NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {AppRoutingModule} from "./app-routing.module";
import {LoginComponent} from "./login/login.component";
import {MainComponent} from "./main/main.component";
import {AuthService} from "./services/auth.service";
import { provideAuth } from 'angular2-jwt';

@NgModule({
    imports     : [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        LoginComponent,
        MainComponent
    ],
    providers   : [
        AuthService,
        provideAuth({
          noJwtError: true,
        })
    ],
    bootstrap   : [AppComponent]
})
export class AppModule
{
}

更多信息在这里

编辑:

带有错误处理程序的AuthService:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp, AuthHttpError } from "angular2-jwt"; //we need to import the AuthHttpError

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        })
        .catch(this.handleError); // we had the catch
    }

    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof AuthHttpError) {
          //here we will handle JWT errors
          console.log(error)
        } else if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        }else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

That's the default behaviour of angular2-jwt

By default, if there is no valid JWT saved, AuthHttp will return an Observable error with 'Invalid JWT'. If you would like to continue with an unauthenticated request instead, you can set noJwtError to true.

You should only use AuthHttp when you want to do authenticated requests, so on your AuthService you also need to import the Http service, something like this:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp } from "angular2-jwt";

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        });
    }
}

As said before Angular2-jwt checks for a valid JWT token, if by any chances there isn't a valid JWT then it doesn't even do the request.

But if you want to use authHttp for every request you can disable the JWT token validation, by overriding the configs of the provider, on your app.modute.ts add it like this:

import {NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {AppRoutingModule} from "./app-routing.module";
import {LoginComponent} from "./login/login.component";
import {MainComponent} from "./main/main.component";
import {AuthService} from "./services/auth.service";
import { provideAuth } from 'angular2-jwt';

@NgModule({
    imports     : [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        LoginComponent,
        MainComponent
    ],
    providers   : [
        AuthService,
        provideAuth({
          noJwtError: true,
        })
    ],
    bootstrap   : [AppComponent]
})
export class AppModule
{
}

more info here

EDIT:

The AuthService with the error handler:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp, AuthHttpError } from "angular2-jwt"; //we need to import the AuthHttpError

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        })
        .catch(this.handleError); // we had the catch
    }

    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof AuthHttpError) {
          //here we will handle JWT errors
          console.log(error)
        } else if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        }else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

相关问答

更多
  • JWT类位于命名空间Firebase\JWT ,因此您需要use它: use \Firebase\Jwt\Jwt; Jwt::encode(...); 或者在调用时使用其完整命名空间: \Firebase\Jwt\Jwt::encode(); If you copied the file from GitHub rather than using composer to install it, you will need to comment out the namespace lines at the ...
  • auth.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { environment } from '../../environments/environment'; import { tok ...
  • 这是angular2-jwt的默认行为 默认情况下,如果没有保存有效的JWT , AuthHttp将返回带有“无效JWT”的Observable错误 。 如果您希望继续使用未经身份验证的请求,则可以将noJwtError设置为true 。 您只应在要进行经过身份验证的请求时使用AuthHttp ,因此在您的AuthService上还需要导入Http服务,如下所示: import { Injectable } from "@angular/core"; import { Http, Response} fro ...
  • 这被解决了。 但是我升级到python3。 import requests import urllib3 urllib3.disable_warnings() payload = { 'username': 'testuser', 'password': 'test1234' } base_url = 'https://www.example.com/api/v1/' api_auth = base_url + 'api-token-a ...
  • 实际上使用cookies和JWT令牌是错误的。 JWT令牌比cookie更适合身份验证。 当您使用令牌时,您的服务器不需要将会话存储在内存数据库中,这对您的应用程序来说是一个很大的优势 - 您可以扩展应用程序,添加新服务器而无需考虑如何在服务器之间同步会话。 简而言之,当您使用JWT令牌时,您的流程就是下一个: 前端(在你的情况下,它是一个角度)发送登录和密码到/登录路由 后端检查凭据并发送回令牌(在请求正文中,而不是在cookie中) 前端应用程序将令牌保存在本地存储或浏览器的会话存储中 并且您可以编写H ...
  • 您需要阅读完整的回复,而不仅仅是正文。 请参阅HTTP客户端文档 。 你的电话应该是这样的: this.http.post(url, JSON.stringify({ username: username, password: password }), { observe: 'response' }) .subscribe((response: HttpResponse) => { ... }); You need to read the full response, not just ...
  • 所以,如果有人来到这里,我使用Express来解决这个问题。 https://www.npmjs.com/package/cors 易于使用,只需添加app.use(cors()); 在我的节点服务器中的任何中间件之前。 So, in case anyone gets here, I solved this using a library for Express. https://www.npmjs.com/package/cors Easy to use, just added app.use(cors( ...
  • 首先,可以简化getSubDomain() ,因为您可以直接返回storage.get('club')结果。 正如你所提到的,你的问题是一个异步问题,你可以通过等待承诺结束之前解决它,如下所示: export function getAuthHttp(http: Http, options: RequestOptions) { return getSubDomain().then(subDomain => new AuthHttp(new AuthConfig({ no ...
  • 当您使用刷新令牌(jwt.refresh中间件)时,这是预期的行为。 https://github.com/tymondesigns/jwt-auth/wiki/Authentication 这个中间件将再次尝试从请求中解析出令牌,并反过来刷新令牌(从而使旧令牌无效),并将其作为下一个响应的一部分返回。 这基本上会产生单个使用令牌流,如果令牌受到攻击,则会减少攻击窗口,因为它只对单个请求有效。 如果您不想使用刷新令牌,那么您可以放弃该中间件。 如果您确实想要使用刷新令牌,则需要更新用于每个请求的身份验证的令 ...
  • 基于令牌的认证方案是什么 在基于令牌的认证方案中,令牌成为用户的凭证。 用户名和密码等硬凭证将交换为必须在每个请求中发送的令牌,然后服务器才能执行身份验证/授权。 令牌可以在很短的时间内有效,可以撤销,可以携带范围详细信息(可以使用令牌请求的内容)等。 使用令牌,您必须能够识别定位API的用户。 因此,对于所有经过身份验证的用户,只有一个令牌是没有意义的。 解决您的问题 使用JWT后,您可以使用用户名进行声明。 还要考虑为您的令牌添加到期日期( exp claim)。 你不希望你的令牌永远有效,对吗? 使用 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。