如何从 Angular UI 前端向 Node.js 后端传递字符串参数?

3

我正在尝试将一个字符串值从Angular UI传递到Node.js后端API,然后使用传递的字符串值在MongoDB中进行搜索,如下所示。

我尝试通过enteredValue输入值,并将其作为params: this.enteredValue传递给http.get调用以及传递给Node.js作为req.params,如下所示,如果我硬编码“orgChange”的字符串值,则可以正常工作,但是以某种方式传递参数不起作用并抛出错误?如何修复它有任何指导吗?

html:

<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<hr>
<button (click)="get_change_lifecycle_data()">Search</button>

<p>{{newPost | json }}</p>

组件

import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-change-input',
  templateUrl: './change-input.component.html',
  styleUrls: ['./change-input.component.css']
})


export class ChangeInputComponent  {

constructor(private http: HttpClient) {}

enteredValue : any;
newPost : any;
get_change_lifecycle_data(){
     this.http.get('http://localhost:3000/api/change_life_cycle2',{params:this.enteredValue}).subscribe(response => {
     console.log(response);
      this.newPost = response
      });
}

}

Node.js

如果硬编码字符串值"orgChange",就可以正常工作。

app.get("/api/change_life_cycle", (req, res, next) => {
 Change_life_cycle.find({ orgChange: "51918661" }).then(documents => {
    res.status(200).json({
      message: "Posts fetched successfully!",
      posts: documents
    });
  });
});

使用req.params的API

   app.get("/api/change_life_cycle2", (req, res, next) => {
    console.log(req.body)
     Change_life_cycle.find({ orgChange: req.params }).then(documents => {
        res.status(200).json({
          message: "Posts fetched successfully!",
          posts: documents
        });
      });
    });

错误:--

(node:75156) UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{}" at path "orgChange" for model "change_life_cycle"
    at new CastError (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/error/cast.js:29:11)
    at SchemaString.cast (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/schema/string.js:553:11)
    at SchemaString.SchemaType.applySetters (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/schematype.js:948:12)
    at SchemaString.SchemaType._castForQuery (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/schematype.js:1362:15)
    at SchemaString.castForQuery (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/schema/string.js:609:15)
    at SchemaString.SchemaType.castForQueryWrapper (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/schematype.js:1331:15)
    at cast (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/cast.js:252:34)
    at model.Query.Query.cast (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/query.js:4576:12)
    at model.Query.Query._castConditions (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/query.js:1783:10)
    at model.Query.<anonymous> (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/query.js:1810:8)
    at model.Query._wrappedThunk [as _find] (/Users/username/Downloads/mongodb-03-finished/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
    at process.nextTick (/Users/username/Downloads/mongodb-03-finished/node_modules/kareem/index.js:369:33)
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:75156) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:75156) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2个回答

2

编辑:有三种方法可以将参数传递给express:

  1. req.query --> 在此情况下,是查询参数
  2. req.body --> post请求正文负载
  3. req.params --> url参数中的 /:someParam

所以我错过了它 :) 应该是 req.query.searchKey。

将查询更改为以下内容:您需要使用不同名称传递不同的参数:

this.http.get('http://localhost:3000/api/change_life_cycle2', 
  {
    params:{
    searchKey: this.enteredValue
    }
  }).subscribe(response => {
    console.log(response);
    this.newPost = response
});

在API端读取请求中的参数,可以这样做:

读取请求中的参数,可以像这样:

app.get("/api/change_life_cycle2", (req, res, next) => {
    console.log(req.body)
     Change_life_cycle.find({ orgChange: req.query.searchKey }).then(documents => {
        res.status(200).json({
          message: "Posts fetched successfully!",
          posts: documents
        });
      });
    });

console.log(req.params.searchKey)app.get 调用中显示为 undefined,看起来搜索关键字参数没有传递到 node.js 的 app.get 调用。 - carte blanche
请见编辑,应为rew.query.searchKey,请原谅。 - 3960278

2
你可以试试使用 HttpParams:
get_change_lifecycle_data(){
     const params = new HttpParams().set('params', this.enteredValue);
     this.http.get('http://localhost:3000/api/change_life_cycle2',{params})
     .subscribe(response => {
          console.log(response);
          this.newPost = response
      });
}


node中使用req.query来访问参数:

最初的回答

   app.get("/api/change_life_cycle2", (req, res, next) => {
    console.log(req.body)
     Change_life_cycle.find({ orgChange: req.query.params }).then(documents => {
        res.status(200).json({
          message: "Posts fetched successfully!",
          posts: documents
        });
      });
    });


这会抛出错误 HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:3000/api/change_life_cycle2?params=51918661", ok: false, …} - carte blanche
@user2125827 你能检查一下拼写等问题吗?404是指URL未找到。/api/change_life_cycle2 - Shashank Vivek
1
你是对的,确实有一个打字错误 :-),现在它可以工作了,非常感谢。 - carte blanche

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接