尝试通过角度

时间:2018-04-23 07:57:56

标签: javascript node.js angular rest typescript

我正在尝试建立一个客户可以看到他所有添加的产品的页面。为了从数据库中获取它们,我编写了一个帖子路由,我按用户名选择数据。我已经使用Advanced REST客户端测试了此请求,但它确实有效。

routes.js

router.post('/myProducts', (req, res, next) => {

const username = req.body.username;

Product.getProductByUsername(username, (err, products) => {
    if (err){
        res.json({
            success: false,
            message: "Something went wrong!"
        });
        console.log(err);
    }
    else {
        res.json({
            success: true,
            message: "List of products retrieved!",
            products
        });
    }
});
});

高级REST客户端响应

{
"success": true,
"message": "List of products retrieved!",
"products": [
  {
"_id": "5adbac5e9eb619106ff65a39",
"name": "Car",
"price": 200,
"quantity": 1,
"username": "testUser",
"__v": 0
},
  {
"_id": "5adc43049eb619106ff65a3a",
"name": "Lipstick",
"price": 2.3,
"quantity": 1,
"username": "testUser",
"__v": 0
},
  {
"_id": "5adcf21c18fe1e13bc3b453d",
"name": "SuperCar",
"price": 2000,
"quantity": 1,
"username": "testUser",
"__v": 0
}
],
}

之后我编写了一个服务将这些数据传递给前端 的 product.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ProductService {

  username: any;

  constructor(private http: Http) { }

  getProducts(username):any{
    console.log(username);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/products/myProducts', username, {headers: headers})
      .map(res => res.json());
  }
}

并尝试在我的组件中使用此服务从POST请求中获取数据。 的 myproducts.component.ts

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

@Component({
  selector: 'app-myproducts',
  templateUrl: './myproducts.component.html',
  styleUrls: ['./myproducts.component.css']
})
export class MyproductsComponent implements OnInit {

  userString: any;
  user:any;
  username: String;

  products: Object;

  constructor(private productService: ProductService) { }

  ngOnInit() {
    this.userString = localStorage.getItem('user');
    this.user = JSON.parse(this.userString);
    this.username =  this.user.username;
    console.log(this.username);

    this.productService.getProducts(this.username).subscribe(myProducts => {
      this.products = myProducts.products;
    },
    err => {
      console.log(err);
      return false;
    });
  }
}

我相信我在这里做错了什么。因为我得到404 BAD请求然后解析错误,因为请求期望响应在json中但由于错误请求而在html中获取它。你能帮我搞清楚我做错了什么吗?我几乎是自学成才,对我来说理解所有这些都很复杂。谢谢!

1 个答案:

答案 0 :(得分:0)

您的问题在于您如何发送用户名。这是一个字符串,而在服务器req.body是一个对象,它正在寻找一个它找不到的名为username的密钥。

因此,您可以改为发送对象:

return this.http.post('http://localhost:3000/products/myProducts', {username : username},
                      {headers: headers}).map(res => res.json());//^^^^ HERE ^^^^^^^^^^