'Angular 10 Getting status not found error

Hello my application consist of a user search, when the user types in the box the search criteria there should be a search in the database to see if it exist. As soon as I began typing in the there is an error in the console that http:localhost/4200/api/getProducts is not found. I am connecting to the database on port 3000 successfully.

This is the proxy.config.json file:

{
    "/api/*": {
        "target": "http://localhost:3000",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug",
        "pathRewrite": {
            "^/api": ""
        }            
    }
}

server.js file:

const express = require('express');
Product = require('./liveSearch');
const mongoose = require('mongoose');
        
mongoose.connect('mongodb://localhost/productLiveSearch' { useNewUrlParser: true, useUnifiedTopology: true, });

const db = mongoose.connection;

db.on('error', error => console.log(error));
db.once('open', () =>{        
    const app = express();
    app.use(express.json());
    app.use(express.urlencoded({extended: true}));
                     
    app.use(function(req,res,next) {
        res.setHeader( 'Access-Control-Allow-Headers', 'Accept, Accept- Language, Content-Language, Content-Type');
        // res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.header("Access-Control-Allow-Headers", "Content-Type", "Authorization");
        // res.setHeader('Access-Control-Allow-Origin','http://localhost:4200');
        // res.setHeader('Access-Control-Allow-Methods','http://localhost:4200','POST, GET');
        res.setHeader('Access-Control-Allow-Methods','POST, GET ,DELETE, PUT');
        // res.setHeader('Access-Control-Allow- Credentials','http://localhost:4200', true);
        next();
    });
         
    app.post('/getProducts', async(req,res) =>{
        let payload = req.body.payload;
        let search = await Product.find({
            name: {
                $regex: new RegExp('^'+payload+'.*','i')
            }
        }).exec();
        // Limit search to 10
        search = search.slice(0, 10);

        res.send({ payload:search });
    })
});
               
const app = express();        
app.listen(process.env.Port|| 3000, () => {
    console.log("Server has started on Port 3000");  
});
 
app.get('/', function(req, res) {
    res.send('hello world');
});        

My service search.service.ts:

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {map} from 'rxjs/operators'
import { Product } from '@app/models/product';
import { Observable } from 'rxjs';
import { baseUrl } from '@app/config/api';
        
@Injectable({
    providedIn: 'root'
})
    
export class SearchService {
    
    /*not sure if this is needed*/
    baseUrl = 'http://localhost:3000/api/getProducts';
        
    constructor(private http:HttpClient) { }
                
    searchProducts(query:string) {
        return this.http.post<{payload: Array<Product>}>('/api/getProducts',
        {
            payload:query
        }, {
            headers:new HttpHeaders({'Content-Type': 'application.json'
        })
    }).pipe(map(data =>data.payload));
        console.log("Does it make it to the end");
    }
    
    /* not sure if I need this it is never called*/
    getProducts():Observable<Product[]> {
        return this.http.get<Product[]>(this.baseUrl)
    }
}

liveSearch.js file:

const productSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    }
});
        
module.exports = mongoose.model('Product', productSchema);

my header.ts:

import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';
import {NgbModal, ModalDismissReasons, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { SearchService } from '@app/services/search.service'; 
import { User } from '@app/_models';
import { SearchComponent } from '../search/search.component';
    
@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
})
    
export class HeaderComponent {
    /* This is for my search criteria, products is my database collection
    products:Array<Product> = [];
    hasQuery: Boolean = false;
    searchTerm: string;
    user: User;
        
    sendData(event:any) {
        console.log(event.target.value);
        let query:string=event.target.value;
        // Will match if query is nothing or only spaces
        let matchSpaces:any=query.match(/\s*/);
        console.log("What about match");
        if (matchSpaces[0] === query) {
            console.log("What about query");
            this.products=[];
            this.hasQuery = true;
           
            return
        }
        this.searchService.searchProducts(query.trim()).subscribe(results => {
            this.products = results;
            this.hasQuery = true;
            console.log("Trying see if it reached here" + results);
        })
    
        this.searchService.getProducts().subscribe(someresult => {
            this.products=someresult;
            console.log("What does this get me", + someresult)
        })      
    }
} 

I have tried everything in my knowledge base. I have included all of the output I have received in hopes that someone can point me in the right direction.
Thanking You In Advance. PDH



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source