How to make post request from angular to node server - node.js

When I print contents of request on Node server, I can't see the user data anywhere.
Here is my Node server:
var http = require('http');
http.createServer( function (request, response) {
console.log(request);
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
And here is Angular2 code:
import { Component, OnInit } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import { Http, Response, Headers , RequestOptions } from "#angular/http";
import 'rxjs/add/operator/retry'; // to be able to retry when error occurs
import { Observable } from "rxjs/Rx";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'Angular Test';
user = { id : 1, name : "Hello"};
constructor (private http: Http) {}
ngOnInit(): void {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(this.user);
this.http.post("http://localhost:8080/", this.user, options)
.subscribe(
(err) => {
if(err) console.log(err);
console.log("Success");
});
}
}
Can anyone help me out or explain how to handle http request in angular.

That is your server:
const express = require('express')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}) );
app.all("/*", function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.post('/ping', function (req, res) {
res.send(req.body)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
That is your angular client:
import { Component } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = { id : 1, name : 'Hello'};
constructor(private http: HttpClient) { }
callServer() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post('http://127.0.0.1:3000/ping', JSON.stringify(this.user), {
headers: headers
})
.subscribe(data => {
console.log(data);
});
}
}
repo https://github.com/kuncevic/angular-httpclient-examples

I've written this inside our documentation page but since it is deprecated now I'll copy it here.
Your node part, app.js, should look like (assuming you are using expressjs along with node.js):
app.js:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require('body-parser');
server.listen(process.env.PORT || 8080, function(){
console.log("Server connected. Listening on port: " + (process.env.PORT || 8080));
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}) );
app.use( express.static(__dirname + '/front' ) );
app.post('/test', function(req,res){ //**** http request receiver ****
var myTestVar = "Hello World";
return res.send(myTestVar);
});
//send the index.html on every page refresh and let angular handle the routing
app.get('/*', function(req, res, next) {
console.log("Reloading");
res.sendFile('index.html', { root: __dirname });
});
With this node configs when you post something to localhost:8080/test, you will receive myTestVar as a response in your subscribe callback.

Related

CORS not allowing access

I have looked at and troubleshot with many different posts on stack overflow of people having similar or the same issue, however, no solutions seem to work for me.
I keep getting the error
Access to XMLHttpRequest at 'http://localhost:3000/email?email=j' from origin 'https://mai...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I thought adding app.use(cors()); would fix it, but the problem persists.
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
var userController = require("./controllers/userController.js");
var emailController = require("./controllers/emailController.js");
var app = express();
app.use(cors());
mongoose.connect(
"redactedForStackOverflow",
{ useUnifiedTopology: true, useNewUrlParser: true },
err => {
if (!err) console.log("MongoDB connection succeeded...");
else
console.log(
"Error in DB connection : " + JSON.stringify(err, undefined, 2)
);
}
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/", express.static(path.join(__dirname, "angular")));
var port = 3000;
app.listen(process.env.PORT || port, () =>
console.log("Server started at port : " + port)
);
app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
module.exports = app;
EDIT
Adding service file
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/operator/toPromise';
import { User } from './user.model';
import { UserComponent } from '../user/user.component';
#Injectable({
providedIn: 'root'
})
export class UserService {
selectedUser: User;
users: User[];
readonly baseURL = 'http://localhost:3000/users';
codeSentIn;
constructor(private http: HttpClient) {}
postUser(users: User) {
const codeOnItsWay = this.codeSentIn;
this.resetCode();
return this.http.post<any>(this.baseURL, {users, codeOnItsWay});
}
resetCode() {
this.codeSentIn = '';
}
getUserList() {
return this.http.get(this.baseURL);
}
getSpecificUser(id) {
return this.http.get<any>(this.baseURL + '/' + id);
}
findPositionInLine(email) {
return this.http.get<any>(this.baseURL + '/positionInLine/' + email);
}
getUserForLogin(email) {
return this.http.get(this.baseURL + '/login/' + email);
}
sendEmailToCheck(emailToCheck) {
return this.http.get('http://localhost:3000/email', { params: { email: emailToCheck }});
}
}
Update: possible missing cors option:
var corsOptions = {
origin: 'localhost:3000',
credentials : true
}
as mentioned from here : Node JS CORS module not setting Access-Control-Allow-Credentials header
Alternatively, Remove app.use(cors());
You can manually add header in all your requests :
app.use((req, res,next) => {
res.set('Access-Control-Allow-Origin', '*');
next();
});
Just add the above code block before
app.use("/users", userController);
app.use("/email", emailController);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});

how to transfer xml created in angular to a file in node.js

i wanna use it every time from my bpmn project in angular post xml created in a Separate file inside my backend .For this I created a directory in backend.The following codes is in node.js
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var http = require('http');
cors = require('cors');
var app = express();
app.use(cors());
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function(req, res) {
let body = '';
let dir = './example-dir';
req.on('data', function(data) {
body += data;
});
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
req.on('end', function() {
fs.writeFile(dir + '/result.xml', body, function(err) {
if (err) {
return console.log(err);
}
res.send('You just created new xml file!')
});
});
})
const port = process.env.PORT || 3000;
app.set('port', port);
var server = http.createServer(app)
server = app.listen(port, () => {
console.log('Connected to port ' + port )
})
i created a restapi.service.ts :
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class RestapiService {
apiURL = 'http://localhost:3000';
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/xml'
})
}
savexml(item):Observable<{}>{
return this.http.post(this.apiURL,item, this.httpOptions)
.pipe(
retry(1)
)
}
The following codes is in app.component.ts :
export class AppComponent implements OnInit {
title = 'MyAngularBPMNTest';
modeler;
form: any[];
constructor(private http: RestapiService , private Http :HttpClient ) {
}
ngOnInit(): void {
this.modeler = new Modeler({
container: '#canvas',
width: '100%',
height: '600px',
additionalModules: [
PropertiesPanelModule,
// Re-use original bpmn-properties-module, see CustomPropsProvider
{[InjectionNames.bpmnPropertiesProvider]: ['type', OriginalPropertiesProvider.propertiesProvider[1]]},
{[InjectionNames.propertiesProvider]: ['type', CustomPropsProvider]},
// Re-use original palette, see CustomPaletteProvider
{[InjectionNames.originalPaletteProvider]: ['type', OriginalPaletteProvider]},
{[InjectionNames.paletteProvider]: ['type', CustomPaletteProvider]},
],
propertiesPanel: {
parent: '#properties'
}
,
moddleExtension: {
custom: customModdle
}
});
this.load();
}
handleError(err: any) {
if (err) {
console.warn('Ups, error: ', err);
}
}
load(): void {
const url = '/assets/bpmn/initial.bpmn';
this.Http.get(url, {
headers: {observe: 'response'}, responseType: 'text'
}).subscribe(
(x: any) => {
console.log('Fetched XML, now importing: ', x);
this.modeler.importXML(x, this.handleError);
},
this.handleError
);
}
save(): void {
this.modeler.saveXML((err: any, xml: any) =>
this.form =xml);
// console.log('Result of saving XML: ', err, xml));
this.http.savexml(this.form).subscribe((data) => {
console.log(data);
}
)}
}
i tried post xml created in node but nothing happened!! in fact gave me this error
" Error Code: 200
Message: Http failure during parsing for http://localhost:3000/"
please help me!!
It seems you want to just upload a file on your server. The nodejs logic you implemented shouldn't work because of its async nature and it seems you're trying to put all your data into the body in a non standard way that can include headers and some other unwanted data.
Since you're already using an HTTP request on Express and your goal in the end is just to upload a file, you may want to use multer.
In this case you're going to pass the xml file on Angular with 'Content-Type': 'multipart/form-data' and by giving a name to the file that Express will recognize:
For instance (taken originally from the official library's github linked above and adapted):
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="xml-name-up-to-you" />
</form>
Once you've implemented this part on Angular, you can write something like this on your Express application:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' }) // folder in which the upload will be saved
var app = express()
app.post('/', upload.single('xml-name-up-to-you'), function (req, res, next) {
// req.file is the `xml-name-up-to-you` file
// req.body will hold the text fields, if there were any
})

Angular Nodejs : Output is Undefined, Can't access the data from the server

I've just started programming in Node and Angular and I'm trying to run a simple application wherein I'm connecting my backend (localhost:3000) to my frontend and displaying the data. If the data I receive from the server when a get request is made is put in a .json file and I access it in the same folder then the data is being displayed.
But if I use the address of the api(http://localhost:3000/purchase) from which the data has been picked I get an undefined error in the browser.
This is the error it shows in the browser:
ContactsComponent.html:2 ERROR TypeError: Cannot read property 'Empno' of undefined
at Object.eval [as updateRenderer] (ContactsComponent.html:2)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:22503)
at checkAndUpdateView (core.js:21878)
at callViewAction (core.js:22114)
at execComponentViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21879)
at callViewAction (core.js:22114)
at execComponentViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21879)
at callWithDebugContext (core.js:22767)
This is the Output from my server (http://localhost:3000/purchase) on Postman:
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
This is the code in angular for the service:
import { Injectable } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClient } from '#angular/common/http';
import 'rxjs/add/operator/map';
import { map, filter, switchMap, catchError } from 'rxjs/operators';
import { Contact } from './contact';
import { HttpErrorResponse, HttpResponse } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class ContactService {
contact: Contact[];
// configUrl1 = '../assets/test.json';
configUrl1 = 'http://localhost:3000';
constructor(private http: HttpClient) { }
// retrieving contacts
getPurchase() {
return this.http.get(this.configUrl1);
}
}
**This is the code for the Component:**
import { Component, OnInit } from '#angular/core';
import { ContactService } from '../contact.service';
import { Contact } from '../contact';
#Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.scss'],
providers: [ContactService]
})
export class ContactsComponent implements OnInit {
contact: Contact;
Empno: string;
Ename: string;
Sal: string;
Deptno: string;
constructor(private contactService: ContactService) { }
ngOnInit() {
this.contactService.getPurchase()
.subscribe((data: Contact) => this.contact = {...data});
}
}
This is the code for defining the structure for contact:
export class Contact {
Empno: string;
Ename: string;
Sal: string;
Deptno: string;
}
This is the code for the HTML file of the contact component:
<div class= "container">
<p>Its Working here also</p>
{{contact.Empno}}
{{contact.Ename}}
</div>
Server Side code:
App.js
//importing modules
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var mssql = require('mssql');
var path = require('path');
var app = express();
const route = require('./routes/route');
//port no
const port = 3000;
// adding middlewear - cors
app.use(cors());
// adding middlewear - bodyparser
// app.use(bodyparser.json());
// static files
app.use(express.static(path.join(__dirname, 'public')));
//creating routes
app.use('/purchase', route);
//testing
app.get('/', (req,res)=>{
res.send('foobar');
});
// //bind the port
app.listen(port, () => {
console.log('Server started at port: ' + port);
});
// create application/json parser
var jsonParser = bodyParser.json()
// app.use(bodyParser.json({ type: 'application/*+json' }))
// POST /login gets urlencoded bodies
app.post('/login', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
route.js
const express = require('express');
const router = express.Router();
var bodyParser = require('body-parser');
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1#ASPL-AVG:1433/Sampledb';
app.use(bodyParser.json());
var jsonParser = bodyParser.json()
router.get('/', jsonParser,(req,res, next)=>{
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.execute('SelEmpl10', function(err, recordset) {
res.json(recordset.recordsets[0][1]);
console.log(recordset.recordsets[0][1]);
})
})
});
//add purchase order
router.post('/' , jsonParser ,(req, res, next) => {
//logic to add record
console.log(req.body.username);
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.input('Username', sql.VarChar(30), req.body.username);
sqlreq.input('Password', sql.VarChar(30), req.body.password);
sqlreq.input('Email', sql.VarChar(30), req.body.email);
sqlreq.input('Name', sql.VarChar(30), req.body.name);
sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
conn.close();
}).catch(function(err) {
res.json({msg: 'Failed to add contact'});
console.log(err);
});
});
})
//delete purchase order
router.delete('/:id', (req, res, next) => {
//logic to delete record
});
module.exports = router;
The data received from SQL is this:
{
"recordsets": [
[
{
"Empno": "112 ",
"Ename": "john ",
"Sal": "142500 ",
"Deptno": "CS "
},
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
]
],
"recordset": [
{
"Empno": "112 ",
"Ename": "john ",
"Sal": "142500 ",
"Deptno": "CS "
},
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
],
"output": {},
"rowsAffected": [
2
],
"returnValue": 0
}
After adding the parameters in Node the output is this:
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
The issue is possibly connected to the use of bodyParser. It may be trying to parse already parsed JSON. Basically add the parser once at the top level and remove it from the routes. Also it may be connected to using json() instead of send(). I’ve had issues where if the data had a property named data, it could cause json parse/stringify to fail.
Try the following. In App.js reintroduce the line app.use(bodyParser.json()), this only needs to be added once at a top level location such as this entry file. Also from this file remove jsonParser middleware from the /login POST route:
var bodyParser = require('body-parser');
var app = express();
const route = require('./routes/route');
//port no
const port = 3000;
// adding middlewear - cors
app.use(cors());
// adding middlewear - bodyparser
app.use(bodyParser.json());
// static files
app.use(express.static(path.join(__dirname, 'public')));
//creating routes
app.use('/purchase', route);
//testing
app.get('/', (req,res)=>{
res.send('foobar');
});
// //bind the port
app.listen(port, () => {
console.log('Server started at port: ' + port);
});
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
In route.js, remove the bodyParser.json() and jsonParser middleware, it's already included at the top level as app.use(bodyParser.json()); applies it to all routes/verbs:
const express = require('express');
const router = express.Router();
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1#ASPL-AVG:1433/Sampledb';
router.get('/',(req, res, next)=>{
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.execute('SelEmpl10', function(err, recordset) {
res.json(recordset.recordsets[0][1]);
console.log(recordset.recordsets[0][1]);
})
})
});
//add purchase order
router.post('/', (req, res, next) => {
//logic to add record
console.log(req.body.username);
var conn = new sql.ConnectionPool(config);
conn.connect().then((conn) => {
var sqlreq = new sql.Request(conn);
sqlreq.input('Username', sql.VarChar(30), req.body.username);
sqlreq.input('Password', sql.VarChar(30), req.body.password);
sqlreq.input('Email', sql.VarChar(30), req.body.email);
sqlreq.input('Name', sql.VarChar(30), req.body.name);
sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
conn.close();
}).catch(function(err) {
res.json({msg: 'Failed to add contact'});
console.log(err);
});
});
})
// delete purchase order
router.delete('/:id', (req, res, next) => {
//logic to delete record
});
module.exports = router;
If that still fails, try just using res.send() instead of res.json(), even just for troubleshooting purposes.
The last thing that I'd recommend is sending an actual error or at least some type of 4xx or 5xx status code so that Angular HttpClient can treat it as an actual error instead of a successful HTTP request with a 200 status code.
Hopefully that helps!
Add a safe navigation operation to the contact variable.
<div class= "container">
<p>Its Working here also</p>
{{contact?.Empno}}
{{contact?.Ename}}
</div>
which is equivalent to contact != null ? contact.Empno: null
Update:
Also, add Error Handling code:
ngOnInit() {
this.contactService.getPurchase().subscribe(
(data: Contact) => {
this.contact = {...data};
},
error => {
console.log("Error Occured: "+ error);
}
);
}

Getting error Response with status: 404 Not Found for URL

I am facing an issue while running the angular and nodejs app which I am trying to integrate with Neo4j app. The issues are the errors that I get-
POST http://localhost:7474/viewNodesStart 404 (Not Found)
and
EXCEPTION: Response with status: 404 Not Found for URL:
http://localhost:7474/viewNodesStart
Though this topic is repetitive in StackOverflow , I am still posting it because the following links suggestions didn't suit my issue.
Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero
EXCEPTION: Response with status: 404 Not Found for URL / Angular2
https://github.com/johnpapa/angular-tour-of-heroes/issues/94
Please check my code
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Injectable } from '#angular/core';
import { ToasterService } from '../toaster.service';
import { FormGroup, FormControl, FormBuilder, Validators } from '#angular/forms';
import { Http, Response, Headers } from '#angular/http';
import { config } from '../config';
import { Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';
import 'rxjs/Rx';
import { Observable } from 'rxjs';
// Statics
import 'rxjs/add/observable/throw';
#Component({
selector: 'app-neo4j-primary',
templateUrl: './neo4j-primary.component.html',
styleUrls: ['./neo4j-primary.component.css']
})
export class Neo4jPrimaryComponent implements OnInit {
constructor(private http: Http, private notify: ToasterService) { }
ngOnInit() {
this.viewNodesStart();
}
emptyObj;
info;
// ------------------------------- Nodes Entire Data --------------
viewNodesStart() {
console.log("INSIDE viewNodesStart()")
// Nodes Value
console.log("inside Nodes Value");
var data = localStorage.getItem('token');
console.log("data is=>",data);
var url = config.url;
var port = config.port;
this.http.post("http://"+url+":"+port+"/viewNodesStart",this.emptyObj)
.map(Response => Response.json())
.subscribe((res: Response) => {
console.log("XXXXXXXXXXXX Response on /viewNodesStart", res);
this.info = res;
console.log('success', this.info.statusCode);
if (this.info.statusCode == 200) {
this.notify.Success("Data added successfully");
} else {
this.notify.Error("Data is not inserted")
}
});
}
}
server.js
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
const neo4j = require('neo4j-driver').v1;
var app = express();
var restify = require('restify');
var expressJwt = require('express-jwt');
var session = require('express-session');
var config = require('./config.json')
app.use(restify.plugins.bodyParser());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}))
app.use(cors());
app.use(session({
secret: config.secret,
resave: false,
saveUninitialized: true
}));
//*****TM Server ******/
app.use('/viewNodesStart', require('./neo4jserver/tmserver'));
app.get('/', function(req, res) {
res.send('Welcome');
console.log("welcome in console");
});
// start server
var server = app.listen(7473, function() {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
nodeserver.js
// Require Neo4j
var neo4j = require('neo4j-driver').v1;
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var express = require('express');
var router = express.Router();
var app = express();
// Create Driver
const driver = new neo4j.driver("bolt://localhost:11001",neo4j.auth.basic("neo4j", "abc"));
// Run Cypher query
const cypher = 'MATCH (n) RETURN count(n) as count';
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
var session = driver.session();
app.post('/', function(req, res) {
console.log("INSIDE NODE JS CONTROLLER OF viewNodesStart");
console.log("BODY IS ", req.body);
var log = JSON.parse(req.body);
console.log(log);
session.run('MATCH (n) RETURN n LIMIT 25').then(function(result) {
result.records.forEach(function(record) {
console.log("record", record);
console.log("result = ", result)
console.log("record._fields[0].properties", record._fields[0].properties);
res.status(200).send({
statusCode: '200',
result: result
});
});
}).catch(function(err) {
console.log(err);
}).then(res=>{
console.log("res.records.length", res.records.length);
}
)
res.send('It Works');
res.send(result);
});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === "OPTIONS")
res.send(200);
else
next();
}
console.log('Server started on port 11005');
module.exports = router;
module.exports = app;
I guess the problem is with the url you are passing to the http request. You are passing the path of the anuglar route and want to call the node api.
Change the url there to the nodeapi url. Then it will work.

NodeJS server can't retrive post data from Angular

I have a backend server writen in NodeJS, which use express.
I have the latest Angular as frontend, I post a data (GPG file) to the nodeJS server, and I try to get that data in NodeJS code, and print it out in the server console, but all I get is an empty object.
All I want to do is to either pass the Blob data to node server, or to pass a plain text to node server, and read it from node code.
const express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
const cors = require('cors');
app.use(cors());
//create a cors middleware
app.use(function (req, res, next) {
//set headers to allow cross origin request.
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/decrypt', (res, req) => {
// Here I try to access the data that I passed by POST method
console.log(res.body);
return 'data back';
})
This is my Angular Code:
import { Injectable, Input } from '#angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '#angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Observable';
import { saveAs } from 'file-saver/FileSaver';
#Injectable()
export class DatabaseService {
private API_GET_LIST_FILES = 'http://localhost:3000/files';
private API_GET_FILE = 'http://localhost:3000/download?name=';
private BASE_URL = 'http://localhost:3000/';
constructor(private http: HttpClient) { }
getFile(key: string) {
return this.http.get(this.API_GET_FILE + key, {
responseType: 'blob'
})
.map(res => {
return {
filename: key.split('/').pop(),
data: res
};
})
.subscribe(res => {
console.log('start download:', res);
// no matter what I pass here to the decrypt function, I can't get it in nodeJS server
this.decrypt(res.filename)
.subscribe(
next => console.log(next)
);
saveAs(res.data, res.filename);
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.');
});
}
decrypt(res): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/octet-stream'
})
};
return this.http.post(this.BASE_URL + 'decrypt', res, httpOptions);
}
}
If I pass the ***res*** to the decrypt function, I will get a lot info but looks weird to me.
Do what Anand suggested, set headers to application/json (or just skip httpOptions completely as that is default) and send {name: res}. Request body then should be just that.
For file upload you should use Express middleware like Multer or Multiparty. On Angular side for example ng2-file-upload.
Express method callback signature is (req, res, next) not (res, req), it is confusing when reading your code :(
And if you just return from callback, it will hang until http request times out (I think). You should do res.status(200).end() or res.json({done: true}) or anything similar.

Resources