繁体   English   中英

尝试通过角度服务通过服务发送请求时,错误请求404

[英]Bad request 404 when trying to POST request via service in angular

我正在尝试创建一个页面,以便客户可以看到他所有添加的产品。 为了从数据库中获取它们,我编写了一个发布路线,在其中我要按用户名选择数据。 我已经使用高级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
}
],
}

之后,我编写了将这些数据传递给前端的服务。
产品服务

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中获取。 您能帮我弄清楚我做错了什么吗? 我几乎是自学成才的,对我来说,要理解所有这些还有些复杂。 谢谢!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM