Reputation: 75
Basically my Angular App should do an HTTP-Get Request and the Express server (which also hosts the angular app) should send an JSON object to the Angular app. Somehow it doesn't work and I have no clue why. Even the first console.log on my Server.js get method wont get called.
Server.js :
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, '../dist/appTest')));
app.use(bodyParser.json({
limit: '5mb'
}));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Accept');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get('*', (req, res, next) => {
res.sendFile(path.join(__dirname, '../dist/appTest/index.html'))
});
app.get("/api/getData", function(req,res) {
console.log("get123");
var testObj = {
"name": "TestName",
"email": "[email protected]",
"subject": "TestSubject",
"content": "Some text...",
"answer": [{
"date": newDate(Date.now()).toLocaleString(),
"sender":"Mr.Test",
"answer":"some text.."
}]
}
console.log("get456");
res.json(testObj)
});
app.listen(3000, () => console.log('Server running on port 3000!'));
The Angular service im using :
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class DbConnectorService {
private baseUrl:string = "http://localhost:3000"
constructor(private http: Http) { }
getAllData() {
this.http.get(this.baseUrl + '/api/getData').subscribe((res) => {
console.log(res);
});
}
}
The console.log in the service prints out the following :
Response {_body: "<!doctype html>↵<html lang="en">↵<head>↵ <meta ch…="main-es5.js" nomodule></script></body>↵</html>↵", status: 200, ok: true, statusText: "OK", headers: Headers
My goal is to get the Object "testObj" from the server to the Angular App with a get request(printing it on the browser console is enough for now). And Im also wondering why the console.logs in the app.get("/api/getData", function(req,res)
won't get printed. Does that mean that route never gets called? But why?
Upvotes: 0
Views: 604
Reputation: 196
When define app.get('*', function()= {})
it take every HTTP request and handle it by its callback. I can see your response from the api containing HTML data from a file so in this case, your api process this block code, not the /api/getData
.
app.get('*', (req, res, next) => {
res.sendFile(path.join(__dirname, '../dist/appTest/index.html'))
});
Upvotes: 1