javascript - 尝试通过 Angular 服务 POST 请求时出现错误请求 404

标签 javascript node.js angular rest typescript

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

之后,我编写了一个服务来将此数据传递给前端。
产品.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 格式获取响应。你能帮我弄清楚我做错了什么吗?我几乎是自学成才的,但理解这一切对我来说有点复杂。谢谢!

最佳答案

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

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

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

关于javascript - 尝试通过 Angular 服务 POST 请求时出现错误请求 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976039/

相关文章:

node.js - 保护 NodeJS 的 post 路由

javascript - Node : chaining exec commands with promises

javascript - 如何通过 pubsub 在 shell app 和微应用程序(前端)之间安全通信

javascript - 链接两个 observable http 和存储

javascript - Angular:Bootstrap 4 深色和浅色模式切换

javascript - 更改复选框更改芯片颜色实现 css

javascript - 取消 图片未在 uploadify 中显示

javascript - Electron 中2个浏览器窗口之间的通信

javascript - 菜单出现和消失,过渡效果

javascript - 无法摆脱 webpack-dev-server 状态栏