Tuesday 16 May 2017

Angular 2 App with Express server not responding to API calls

I have a angular2 app hosted on heroku. The server is a node/express one.

Example: When my app makes an api to posts (appurl.com/posts) it is structured as such: appurl.com/api/posts

  • all api calls are made at appurl.com/api/~ whatever
  • all data is sent to appurl.com/~ whatever

However on the live version of my application, every call to the api comes up with a 404. This does not happen when I am developing locally, the api works jsut fine.

I always get this 404 error for each api call I try:

zone.js:2019 GET https://appurl.com/api/posts/ 404 (Not Found)

server.js (express)

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');

let index = require('./server/routes/index');
let posts = require('./server/routes/posts');

let app = express();

const port = process.env.PORT || '3000';

let uriString = process.env.MONGODB_URI || "mongodb://localhost:27017/test-db";
mongoose.connect(uriString, function(err, res) {
    if (err) {
        console.log(err);
    } else {
        console.log('Success connected to: ' + uriString)
    }

});

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/dist'))); //enable for build

app.use(function (req, res, next) {
    var allowedOrigins = ['https://www.appurl.com', 'https://appurl.herokuapp.com', 'https://appurl.com', 'http://localhost:3000'];
    var origin = req.headers.origin;
    if (allowedOrigins.indexOf(origin) > -1) {
        res.setHeader('Access-Control-Allow-Origin', origin);
    }
    // res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS', 'PUT');
    res.header('Access-Control-Allow-Credentials', true);
    return next();
});

app.use('/api/', index);
app.use('/api/posts', posts);


app.get('*', (req, res, next) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.listen(port, () => console.log(`server running on port:${port}`))


module.exports = app;

post.service.ts

    import { Injectable, EventEmitter } from "@angular/core";
    import { Http, Headers, Response } from "@angular/http";
    // observable lib
    import 'rxjs/Rx';
    import 'rxjs/add/operator/map'
    import { Observable } from "rxjs";
    import { Post } from "./post.model";
    import { ErrorService } from '../shared/errors/error.service';
    import { NotificationService } from '../shared/notifications/notification.service';
    import { Router } from '@angular/router';

    const api = '/api/posts/';

    @Injectable()
    export class PostService {
        private posts: Post[] = [];
        private post: Post;
        postIsEdit = new EventEmitter<Post>();

        constructor(private http: Http, private _es: ErrorService, private _ns: NotificationService, private _r: Router) {
        }

        getPosts() {
            return this.http.get(api)
                .map((response: Response) => {
                    const posts = response.json().obj;
                    let transformedPosts: Post[] = [];
                    for (let post of posts) {
                        transformedPosts.push(new Post(
                            post.title,
                            post.description,
                            post.location,
                            post.author,
                            post.user,
                            post.date_created,
                            post.timestamp,
                            post.userId,
                            post._id)
                        );
                    }
                    this.posts = transformedPosts;
                    return transformedPosts;
                })
            // .catch((error: Response) => Observable.throw(error.json()));
        }
}



via aleks

No comments:

Post a Comment