Angular: Error while fetching data from Node API?

Total
1
Shares

I am trying to fetch json data from my Nodejs API using URLlocalhost:3000/articles/publicationData which is running successfully in Postman app but don’t know why is giving error with same url in angular app, but in Angular app it is giving an error –

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:3000/articles/publicationData", ok: false, …}
error: "<!DOCTYPE html>n<html lang="en">n<head>n<meta charset="utf-8">n<title>Error</title>n</head>n<body>n<pre>Cannot GET /articles/publicationData</pre>n</body>n</html>n"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: Æ’}
message: "Http failure response for http://localhost:3000/articles/publicationData: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:3000/articles/publicationData" 

My app-service.ts file is –

import { Injectable } from '@angular/core'; 
import { HttpClient} from '@angular/common/http';
import { AppSetting } from './appsetting'
@Injectable({
  providedIn: 'root'
})
export class AppServiceService {
  private SERVERURL = AppSetting.API;
  constructor(private http: HttpClient) { }

  login(user){
    console.log(user);
    return this.http.post<any>(this.SERVERURL+"users",user);
  }

  getPublication(){
    let url = "http://localhost:3000/articles/publicationData";
    return this.http.get(url);
  }


}

My app.component.ts file

import { Component, OnInit  } from '@angular/core';
import { DatepickerModule } from 'ng2-datepicker';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { DatepickerOptions  } from 'ng2-datepicker';
import { AppServiceService } from './../app-service.service';
import { Subscriber } from 'rxjs';



@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {


  constructor(private http: HttpClient,private auth : AppServiceService, private _router: Router) {
    this.auth.getPublication().subscribe(data => {
      console.warn(data);
    })
   }

  ngOnInit(): void {
    $("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
  });



  }

}
 

Controller.js

    var db = require("../db.js");
var ObjectId = require('mongodb').ObjectID;
var mysql = require('mysql');

var connection = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'pass',
    database: 'name'
});
var publicationData = (req, res) => {
  var sql = `select pub_master.PubId, pub_master.Title,
  pub_master.MastHead, pub_master.Circulation, pub_master.WebSite,
  pub_master.Issn_Num, pub_master.Place, picklist.Name as city
  from pub_master
  join picklist on picklist.id = pub_master.Place
  and picklist.id <> 0`;

  connection.query(sql,[], function (error, results, fields) {
    if (error) {
      res.send({
        "code":400,
        "failed":"error ocurred"
      })
    }else{
      if(results.length >0){
        res.send({
          "code":200,
          result : results
        });
      }
      else{
        res.send({
          "code":204,
          "success":"Email and password does not match"
        });
      }
    }
  });
}
 
 
module.exports = {
  publicationData: publicationData
} 

Publication route

    var express = require("express");
var articlescontroller = require("../controller/articlesController")
var articlesrouter = express.Router();


articlesrouter.route('/publicationData')
.post(articlescontroller.publicationData);  

app.js

    var express = require("express");
const serverless = require('serverless-http');
var moviesrouter = require("./routes/movierouter");
var articlesrouter = require("./routes/articlesrouter");
// var mailarticlerouter = require('./routes/mailarticlerouter');
var bodyParser = require("body-parser");
var mongoos = require("mongoose");





/*****************MYSQL CONNECTION*********************/
var mysql      = require('mysql');
var connection = mysql.createPool({
  host     : '',
  user     : '',
  password : '',
  database : ''
});


/************************************* */


mongoos.set("debug", (collectionName, method, query, doc) => {
    console.log(JSON.stringify(query));
});

mongoos.Promise = Promise;

var db = mongoos.connect("mongodb+srv://aamadmin:[email protected]/impact?retryWrites=true&w=majority",{useUnifiedTopology: true,useNewUrlParser:true});

console.log("connected to mongodb");

var app = express();



var cors = require('cors');
const userrouter = require("./routes/userrouter");

app.use(cors());


app.use(function(req, res, next) {

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();

  });




app.use(bodyParser.json());


var server = app.listen(3000,()=>{
    console.log("server is running on port 3000");
});
server.timeout = 600000;


module.exports.handler = serverless(app);

 
app.use('/articles',articlesrouter); 

Solution

From your Postman screen, you need to send a POST request to localhost:3000/articles/publicationData, not a GET request. You have the 404 error with your code and when trying to access localhost:3000/articles/publicationData in browser because you’re sending GET requests.

In your Angular code, change from :

 getPublication(){
    let url = "http://localhost:3000/articles/publicationData";
    return this.http.get(url);
  }

to :

 getPublication(){
    let url = "http://localhost:3000/articles/publicationData";
    return this.http.post(url, {});
  }
Leave a Reply

Your email address will not be published. Required fields are marked *