Reputation: 2391
I am trying to fetch data from Mongo DB using angular2 and node server via http get request. When I am trying to view the get response in browser ,I can see html tags as value of "_body" but if same http get request is changed to http post then reponse is as below :
"{"success":true,"sellerdata":[]}" as value of "_body".
Why post is working with same code configuration but not get request?
Here is my angular Code. All required imports are present in class.
This is service class where get observable created.
/**(post changes which is working fine)return
this.http.post('/sellerlist',{}).map(**/
@Injectable()
export class AdminService {
constructor(private http:Http) { }
getSellerdata(){
return this.http.get('/sellerlist').map(
(res:Response ) =>{return res.json();})
}}
This is subscriber class where request is initiated and response is logged on browser console.
@Component({selector: 'app-admin-sellers',})
export class AdminSellersComponent implements OnInit {
constructor(private adminService :AdminService) { }
ngOnInit() {
this.adminService.getSellerdata().subscribe(
(dataFromServer) => {console.log(dataFromServer);}); //
}}
Here is my node server JS. All server side configurations are present here.
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
mongoose.Promise = require('bluebird');
mongoose.connect('localhost/testapp')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
console.log(req.body);
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use('/secure/*', secureRoutes);
function secureRoutes(req, res, next) {
var token = req.headers['token'];
if (token) {
jwt.verify(token, process.env.SECRET_KEY, function (err, decode) {
if (err) {
res.status(500).send('Email & Password do not match');
} else {
next();
}});
} else {console.log(2)}};
app.all("/secure/*", secureRoutes, function (req, res, next) {
next();});
app.get('/sellerlist', getSellerList);
/**(post changes which is working fine)
app.post('/sellerlist', getSellerList);**/
Upvotes: 1
Views: 658
Reputation: 2391
Problem was present in server side configuration.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
is written before
app.get('/sellerlist', getSellerList);
So all get requests are handled by the default configuration . After reversing the above order , get requests worked.
Upvotes: 1