如何读取快速节点js api中的参数

时间:2018-01-12 12:48:20

标签: javascript node.js api express angular5

我创建了angular5应用程序,我需要显示所选产品的详细信息,我使用express-nodejs api从mongodb获取数据,但没有获取如何读取查询字符串...或者是什么在同一个api中读取请求参数的正确方法。

ngApi-prdDetails / server.js

var express = require('express');
var mongodb = require('mongodb').MongoClient;

var app = express();

var port = process.env.PORT||3000; 
var commanRouter = express.Router();

commanRouter.route('/getPrdDetails')
    .get(function(req,res){

        /*----NOT GETTING prdId---*/
        let prdId =  req.query.ProductId;

        //let prdId =  1008; //-----SHOWING EXPECTED RESULT---//

        var url = 'mongodb://xyz:xyz@ds127536.mlab.com:27536/dbxyz'
        mongodb.connect(url, (err, db) => {  
              if (err) {
                return console.log(err);
              }
              let mydb = db.db("dbxyz");

              let queryM = {"ProductId":prdId};

              mydb.collection('products').find(queryM).toArray(
                function(err,data){
                    if(err)

                       res.status(500).send(err);
                    else
                        res.setHeader('Access-Control-Allow-Origin','*')
                        res.setHeader('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept')
                        res.json(data);
        })
        })

});

app.use('/api', commanRouter);

app.get('/',function(req,res){
    res.send("Working");
});
app.use(express.static(__dirname + '/public'));

app.listen(port, function(){
    console.log("running");
});

产品details.service.ts

@Injectable()

export class ProductService{
    private _prdDetailsUrl= "https://abc-xyz-12345.herokuapp.com/api/getPrdDetails";

    constructor(private _http:Http){ }


    getProductDetails(productId:number):Observable<IProduct[]>{
        let apiURL = `${this._prdDetailsUrl}?ProductId=${productId}`;
        return this._http.get(apiURL)
                    .map((response:Response)=> <IProduct[]>response.json())
                    .catch(this.handleError);
    }


    private handleError(error:Response){
        return Observable.throw(error.json().error || "Server Error!");
    }
}

产品details.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProductService } from './product.service';

import { IProduct } from './product';

@Component({
    templateUrl:'./product-details.component.html',
    styleUrls:['./product-details.component.css']
})

export class ProductDetailsComponent{
    products:IProduct[];
    errorMessage:string;
    pId:number;
    constructor(private _route:ActivatedRoute,
                private _productService:ProductService){

    }

    ngOnInit():void{
        console.log("<<<<<<---------------------This is Product-Details:Init-------------------------->>>>>>");
        let id = this._route.snapshot.params['id'];
        this.pId =id;

        this._productService.getProductDetails(id)
            .subscribe(products => this.products = products,
            error => this.errorMessage = <any>error);
    }
}

1 个答案:

答案 0 :(得分:0)

使用req.params获取路由参数值

let prdId =  req.params.ProductId;