I am running a Express application with Node in the backend. I have 2 functions in a component in NodeJS which I am trying to access from my service. The link for both are the same in the service. It is able to connect one of the functions from the service.
However, it is showing 404 not found for accessing the second function in the same component. It is strange that the 2 functions from the same service is are giving 2 different responses (1 success and 1 failure).
Has anyone faced any such issue and if so how can it be rectified?
Some code for reference :
component1.component.ts
getallprojectcat()
{
this.authenticationService.getprojectcat()
.pipe(first())
.subscribe(
data => {
this.data = data;
},
error => {
this.loading = false;
});
}
}
component2.component.ts
showprojects(moid)
{
this.authenticationService.getprojectslist(moid)
.pipe(first())
.subscribe(
data => {
this.silver = data;
},
error => {
console.log('some error');
this.alertService.error(error);
this.loading = false;
});
}
the .service file
getprojectcat()
{
return this.http.get<any>(this.studenturl+'/getprojectcata/')
.pipe(map(allprojectcat => {
console.log(JSON.stringify(allprojectcat));
return allprojectcat;
}));
}
getprojectslist(moid)
{
return this.http.get(this.studenturl+'/getprojects/'+moid)
.pipe(map(projectslist => {
console.log("Projects List:"+JSON.stringify(projectslist));
return projectslist;
})).catch(this.handleError);
}
Backend .js file
exports.getprojectcata = function(req, res){
console.log("First Function");
};
exports.getprojects = function(req, res){
console.log("Second Function");
};
The function getprojectcata is working in the first component. However, it shows an 404 not found on the getprojects function in the second component. I have checked the following things -
Routing does not seem to be the problem as it is moving to the next component without any issues.
We have also tried calling the getprojectscata through the same service in component and it worked.
For sencond function use .post in service and backend route also.
As GET requests is only used to request data. And you are passing moid in http.get which gives 404.
In post you can send moid data in params and in backend fetch data as req.params.
I hope it wil help you .
Share your code for better understanding.
Related
I am currently working on a web app to manage an external database. I am not very familiar with express or NodeJS at this point so I wanted to ask how to send a JSON object to the client sides console without getting undefined?
I have this function to connect then select the what I need and afterwards I converted my JSON object to an array of JSON objects. It displays the data fine in the console as well.
async function connect() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (err) {
console.error('Unable to connect to the database:', error);
}
info = await sequelize.query('select * from LeadsInformation', { type: QueryTypes.SELECT });
const details = JSON.stringify(info);
console.log(details);
detailsArray = JSON.parse(details);
console.log(detailsArray);
}
Everything works fine in here, I can get the data and display it in the terminal.
This is my GET route:
app.get("/list", (req, res) => {
connect();
res.json(detailsArray)
});
I have tried a couple of suggested ways based on other explanations and code snippets but none of them has worked so far so I left it like that. I thought foreaching through the data itself in the request would be a solution but it did not work. I also tried using the JSON itself and trying to display it and also tried using the body parser library. Though the library has not been updated for two years. Also I am using axios to fetch the data. It works fine when I try sending a simple string like "hello world" for example.
Is there anything that I'm missing or do you have any other solutions? I would also appreciate an explanation as well if possible.
Edit: It might also have to do something with how I am getting the response in the frontend. I'll look into that as well and will update this thread if I sort it out!
This is the way I get the response. I am currently trying to show in the console. I am using axios API.
Axios({
method: "GET",
url: "http://localhost:5000/list",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.json);
});
Probably you have undefined in route because connect function doesn't return anything.
Also connect is an async function it means that it returns Promise and you have to call .then method or use await to get value from it.
Here is the code snippet with fixes that I described above.
async function connect() {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (err) {
console.error('Unable to connect to the database:', error);
}
info = await sequelize.query('select * from LeadsInformation', { type: QueryTypes.SELECT });
const details = JSON.stringify(info);
detailsArray = JSON.parse(details);
return detailsArray;
}
app.get("/list", async (req, res) => {
const result = await connect();
res.json(result)
});
Notice that in the router handler function I also use async and await because I call connect which is an asynchronous function.
The solution above did work and also another problem I had was that I wasn't getting the response correctly.
I ended up getting the response to the frontend after changing my code to the following from:
console.log(res.data.json);
To:
console.log(res.data[1]);
I am trying to deploy a GraphQL server on node.js platform using Azure functions. I have been able to deploy a basic hello world app.
However, I need to get data from a backend API in the resolver. I am not able to get either fetch or request package to work in Azure functions.
Below is my code:
var { graphql, buildSchema } = require('graphql');
var fetch = require('node-fetch');
var request = require('request');
var schema = buildSchema(`
type Query {
myObject: MyObject
}
type MyObject {
someId (data: String) : String
}
`);
var root = {
myObject: () => {
return {
someId: (args) => {
// Code enters till this point.
// I can see context.info messages from here.
// return "hello"; <--- This works perfectly fine.
return request('http://example.com', function (error, response, body) {
// -----> Code never enters here.
return body;
});
}
}
}
};
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
graphql(schema, req.body, root)
.then(response => {
context.res = {
body: JSON.strigify(response)
};
context.done();
});
};
I have tried using fetch and request modules. But with both of them, I see the same behavior - the response never returns. The request eventually times out after 5 minutes. If instead of fetch or request, I choose to return some dummy value, I see the response getting returned correctly to the query. With fetch, I don't see the then block or the catch block ever executing.
Note: I have tried both http and https URLs in the request URIs but none of them seem to return any data.
Is it an issue with the way I have implemented the fetch/request or is it an issue with Azure functions in general?
Answering my own question:
It seems that node-fetch and request don't actually return promises. Wrapping the request around Promise seems to solve the problem. Something similar to this answer.
I am calling my get rest service like this,
makeGetCall(url: string): Observable<any> {
const headers = new Headers({'auth-code': 'auth-code',
'from':'app'});
return this.http.get(AdminConstants.BASE_URL + this.SEPARATOR + url,{
headers: headers
})
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
console.log('extract data');
console.log(res);
const body = res.json();
return body || {};
}
private handleErrorObservable(error: Response | any) {
console.log('error in service');
console.log(error.message);
return Observable.throw(error.message || error);
}
and My rest service is:
console.log('inside get all user');
ApiUser.find().then(users => {
console.log('length : '+users.length)
res.status(200).send(users);
}, error => {
res.send(500).send(error);
})
I am using MEAN stack for my application.
Here is my problem, when I am calling my rest service from postman its working.Even in the chrome/mozilla console I can see my response as expected.response header
But from my angular 2 application my handleErrorObservable method is called and that too with an error without proper message.
I just installed ssl certificates on my server, before ssl this was working inside my application.
Also to add post requests are working.
I don't know what I am missing.
Please help.
Thanks in advance.
Thanks to #kirkLarkin
I just added res.set('Access-Control-Allow-Origin','*'); in my rest service and it worked.
Yesterday I faced with unusual behavior for MongoDB.
So.. I store countries and languages with their codes in collections and when client side application need this data - it sends 'get' request to get data. It happens simultaneously
function init() {
helperService
.getCountries()
.then(success)
.catch(commonService.handleError);
function success(res) {
self.countries = res.data;
}
}
function init() {
helperService
.getLanguages()
.then(success)
.catch(commonService.handleError);
function success(res) {
self.languages = res.data;
}
}
Here I send request to get data in angular component $onInit
Backend code looks pretty simple:
var country = require('countryModel');
var language = require('languageModel');
function getCountries(req, res, next) {
return country
.find({})
.then(success)
.catch(next);
function success(data) {
res.json(data);
}
}
function getLanguages(req, res, next) {
return language
.find({})
.then(success)
.catch(next);
function success(data) {
res.json(data);
}
}
Locally all works as expected. But after deploying application on linux server I often see error 404 'Cannot GET /api/language' and 'Cannot GET /api/country'. Sometimes I got data but more often I got one error or this two errors above.
Could anybody give me idea what is wrong?
It seems to me that you have problems with registering routes. Check it please
What I'm trying to do here is,
from /expense/new page submitting POST request to /expense/newPost
on Expressjs, handling this way
app.post('/expense/newPost', function(req, res) { ...
continue, using mongoose I validate the collection as
tmpExp = new Expense(req.body);
tmpExp.validate(function(err) {
if(err || !isValidForm) {
req.session.form.errField = _.extend(req.session.form.errField, (err.errors || err ));
req.session.rePop = req.body;
res.redirect('/expense/new');
} else {
console.log('now saving') // successfully logs here.
tmpExp.save(expPost, function(err2, savedDoc) {
if(err2) {
req.session.flash = {
global: true
, css: "error"
, message: "Internal Server Error"
}
res.redirect('/expense/new');
} else {
res.redirect('/expense/new?success=' + savedDoc.bill_id);
}
});
}
});
for shake of clearity I removed some of the validation code.
Now the problem is, after submitting the POST request by browser data is successfully saved in mongodb but browser not redirect and just waiting for response from server
Your save callback is not passed in properly.
tmpExp.save(expPost, function(err2, savedDoc) {
should be:
tmpExp.save(function(err2, savedDoc) {
Assuming verification code is the only thing you stripped from this file, res is not defined. I'd suggest you just return Error or null and do the remaining logic in the parent function, where res is likely to be present. This also is generally a good practice because your model will be reusable (no path parts in the model)