【问题标题】:Bad request 404 when trying to POST request via service in angular尝试通过角度服务发布请求时出现错误请求 404
【发布时间】:2018-10-03 04:50:07
【问题描述】:

我正在尝试创建一个页面,让客户可以看到他添加的所有产品。为了从数据库中获取它们,我编写了一个帖子路由,我在其中按用户名选择数据。我已经用 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 中得到它。你能帮我弄清楚我做错了什么吗?我几乎是自学成才的,但要理解所有这些对我来说有点复杂。谢谢!

【问题讨论】:

  • 在浏览器的网络选项卡中,您是否看到请求转到了正确的 url?
  • {username:username}这样发送用户名,感觉req.body.username不在请求中。
  • 404 表示 URL 不正确,请在开发控制台中正确检查请求一次
  • 您可以使用postman 测试您的http 请求。这是一个非常有用的工具,可以独立于客户端测试服务器端。
  • @Jai 谢谢!有效!如果您将此作为答案发布,我会将其标记为正确的。

标签: javascript node.js angular rest typescript


【解决方案1】:

您的问题在于您发送用户名的方式。那是一个字符串,而在服务器上 req.body 是一个对象,它正在寻找一个名为 username 的键,但它没有找到。

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

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

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 2019-10-10
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多