Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 错误的请求404,当试图通过服务发布请求时_Javascript_Node.js_Angular_Rest_Typescript - Fatal编程技术网

Javascript 错误的请求404,当试图通过服务发布请求时

Javascript 错误的请求404,当试图通过服务发布请求时,javascript,node.js,angular,rest,typescript,Javascript,Node.js,Angular,Rest,Typescript,我正在尝试制作一个页面,让客户可以看到他添加的所有产品。为了从数据库中获取它们,我编写了一个post路由,其中我通过用户名选择数据。我已经用高级REST客户机测试了这个请求,它可以正常工作 routes.js router.post('/myProducts', (req, res, next) => { const username = req.body.username; Product.getProductByUsername(username, (err, products)

我正在尝试制作一个页面,让客户可以看到他添加的所有产品。为了从数据库中获取它们,我编写了一个post路由,其中我通过用户名选择数据。我已经用高级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
        });
    }
});
});
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());
  }
}
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;
    });
  }
}
高级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
}
],
}
之后,我编写了一个服务,将此数据传递到前端。
产品.服务.ts

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
        });
    }
});
});
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());
  }
}
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;
    });
  }
}
并尝试在我的组件中使用此服务从POST请求中获取数据。 myproducts.component.ts

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
        });
    }
});
});
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());
  }
}
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错误请求,然后解析错误,因为请求期望响应是json格式的,但由于请求错误,所以得到的响应是html格式的。你能帮我找出我做错了什么吗?我几乎是自学成才的,要理解这一切对我来说有点复杂。谢谢

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

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

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

在浏览器的“网络”选项卡中,您是否看到请求指向正确的url?
{username:username}
以这种方式发送用户名,我觉得
req.body.username
不在请求中。404表示url不正确,请在您可以使用测试http请求后在开发控制台中正确检查请求。为了独立于客户端测试服务器端,这是一个非常有用的工具。@Jai谢谢!成功了!如果你把这个作为答案贴出来,我会把它标记为正确答案。