Can't access NodeJS api from Angular app - node.js

I have trouble trying to get to my NodeJs server from my angular app. Here's my router:
app.get('/new12345',function(req,res){
console.log("Http Get Recently Gone from /new12345");
var results = userData;
res.send(results);
});
Here where I try getting to my api.
this.http.get('/new12345').subscribe(data => {
this.resultInArray = data['results'];
}
I am getting this error though:
Error: Cannot match any routes. URL Segment: 'new12345'
Thanks!

You did not specify your api base url. You are currently getting to your angular app (hence the angular router error you are getting).
For example, that might look like this:
this.http.get('http://localhost:3000/new12345').subscribe(data => {
this.resultInArray = data['results'];
}

Related

How to make Passport.js work in Adonis Framework

I wanted to know if Passport.js can ONLY be used in an Express framework and not in any other? The docs doesn't completely answer my question. I'm in the middle of migrating my project from Express to Adonis.js and I can't seem to make passport work. Here is a sample of my code:
const passport = use('passport')
const bearer = use('./bearer')
passport.use('bearer', bearer)
module.exports = passport
and here is how I register it:
const namedMiddleware = {
auth: 'Adonis/Middleware/Auth',
guest: 'Adonis/Middleware/AllowGuestOnly',
bearer: passport.authenticate(['bearer'], { session: false }),
}
this is the usage (I provided a bearer token):
Route.post('/', ({ response }) => {
response.json('Hello world')
}).middleware(['bearer'])
It does not work. Error about res.setHeader is not a function showing. Maybe because the resoponse and http structure is different in adonis?
I know that Adonis has its own authentication library but my INITIAL goal is to get what I have now in Express to work in an Adonis environment before making any library changes to avoid any complications.
I recently migrated from knex to adonis.js as well. Integrating passport.js was initially painful but I get it to work with Macros.
For your error, Adonis' Request object has no setHeader. You will need to create a macro on Request for that function. Something like this
function setHeader (name, value) {
this.header(name, value)
}
Response.macro('setHeader', setHeader)
Add that to a provider or hooks and you should be all set.

angular 4 / res.download from nodejs back-end

I'm calling an Angular component which calls an api service I created to call a nodejs back-end. The back-end download a zip file, using res.download. I believe that the response is not correctly handled, because when I call the back-end directly from the url (localhost:3000/api/download/file), it works perfectly. Here's the code below :
1) Angular component
downloadZipFile(index) {
this._apiService.downloadZip(index).subscribe(data => {
});
}
2) Angular apiService
downloadZip(index) {
return this._http.get('http://localhost:3000' + appConfig.__apiUrl + 'download/' + index);
}
3) NodeJS API
router.get('/download/:index', (req, res) => {
res.download(path.join(__dirname, 'downloads/' + req.params.index + '.zip'));
});
You are attaching multiple time API url in your angular service HTTP request. Please remove one of them. and check again.
downloadZip(index) {
return this._http.get('http://localhost:3000/download/' + index);
}
Add above code in your service.

Small api on node.js

maybe someone have example for creating small API on node.js
Example, i have function this function will return string
I need call this string from postman or inside any another project with http.
What better for create this API?
Maybe someone know good guide? I worked before with node.js only like web-server
It is best practice that building API's in nodejs with express.Here is a code in which function returns a string. You need to export it. And require the file that contains exported value in your project file with the file path. Here is my function code where I am returning a string value. func.js
var string;
function myfunc(param,callback){
var str="hello";
callback(null,str);
}
myfunc('aaa',function(err,result){
if(err){
console.log(err);
}
else{
exports.string=result;
}
});
Here is my routes file and here I am calling the string from func.js and I named this file as str.js
var http = require('http');
var express = require('express');
var main = require('./func.js');//path of file
var org = main.string;
var app = express();
app.get('/str',function(req,res){
console.log(org);
res.send(org);
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
Run the code as node str.js and in postman run the url as http://localhost:3000/str and you can see the returned string in both response and in terminal.
Hope this helps...
This tutorial shows you how to build an API in Node.js with Express.
EDIT: You can skip the database part if you don't need it.

Cannot render my react app server side

I am trying to render a basic react component via node js .
Unfortunately i got some errors. I think this is related to es6.
The problem is i already wrote a lot of code in es6 and now i want to render it in node js. I can't rewrite my entire app, so how to import my components and make them compatible witch node js.
What is what i've tried since now :
const filePath = path.resolve(__dirname, 'index.html')
fs.readFile(filePath, 'utf8', (err, htmlData)=> {
if(err){
return res.status(404).end()
}
const app = renderToString(<ReactApp />)
const RenderedApp = htmlData.replace('{{SSR}}',app)
res.send(RenderedApp)
})
I got this error SyntaxError: Unexpected token <
This is because ReactApp is a react component
i don't know how to import it on my node.
Any solutions ?
thanks

Deleting posted content using $resource in AngularJS

I am new to AngularJS and am trying out a few things with posting and deleting content using $resource. I've got the posting working fine, but when I try to delete something that I've posted I get a 404 error.
DELETE http://localhost:3000/tasks?__v=0&_id=53c5ddcf2978af0000ccdc50&beginningDat…vacy=true&title=This+is+a+complete+task&website=http:%2F%2Fwww.hotmail.com 404 (Not Found)
I've been working on this for a few days now and I'm just not seeing what i am missing. I am using a MEAN stack. I've got mongoose, express, bodyParser, and cors as dependencies in my app.js and created my endpoints:
app.get('/tasks', api.getTask);
app.post('/tasks', api.postTask);
app.delete('/tasks/:_id', api.deleteTask);
Here is the code from my api.js which
exports.deleteTask = function(req, res){
var _id = req.params._id;
Task.remove({_id:_id}, function(err, task){
res.send(task + ' removed task successfully');
if(err){
res.send('Hey guys...he is still here.');
}
});
};
Here is my factory/service:
'use strict';
angular.module('achievementApp').factory('tasks', function($resource){
return $resource('http://localhost:3000/tasks/',{_id: '#_id'},{
get: {method:'GET', isArray: true},
add: {method:'POST'},
delete: {method: 'DELETE'}
});
});
And here is the code from the Ctrl:
$scope.taskList = tasks.get({});
$scope.removeTask = function(obj){
tasks.delete(obj);
var index = $scope.taskList.indexOf(obj);
console.log(index);
$scope.taskList.splice(index,1);
console.log('removeTask was called');
};
Any guidance on this would be greatly appreciated. I've tried just about everything I can to get it to work and have had no luck so far.
It looks like you have a mismatch between the angular code which is putting the _id in the query string and the express code which is looking for it as a route param, which looks in the path part of the URL. req.params comes from the path part before the ?. req.query comes from the query string part after the ?. It would be more conventional to use the path in terms of REST, so I suggest changing your angularjs code to have /tasks/:_id as the resource route.
Aside: Best to use relative paths in your browser JS and omit the protocol, host, and port. Otherwise your app won't work when you deploy it on the real web.

Resources