我在heroku上托管了一个angular2应用。服务器是节点/快速服务器。
示例:当我的应用程序对帖子(appurl.com/posts)发表api时,其结构如下:appurl.com/api/posts
然而,在我的应用程序的实时版本中,每次调用api都会出现404.当我在本地开发时,这种情况不会发生,api工作得很好,以及API和App的版本是两个单独的项目 - 这个版本将被归类为'MEAN2'应用程序,我想,上述问题已经发生......
我尝试每次api调用时都会收到404错误:
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.js(server / routes / post.js)
let express = require('express');
let router = express.Router();
let PostController = require('../controllers/post.js')
let jwt = require('jsonwebtoken');
let User = require('../models/user');
// get posts
router.route('/').get(PostController.getAllPosts); // getAllPosts just returns all posts from the DB, this works locally
module.exports = router;
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()));
}
}
的package.json
{
"name": "testapp",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"heroku-prebuild": "npm install -g http-server",
"heroku-postbuild": "ng build --prod",
"start": "http-server dist/",
"ng": "ng",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update --standalone false --gecko false",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/compiler-cli": "^2.3.1",
"@angular/core": "^2.3.1",
"@angular/forms": "^2.3.1",
"@angular/http": "^2.3.1",
"@angular/platform-browser": "^2.3.1",
"@angular/platform-browser-dynamic": "^2.3.1",
"@angular/router": "^3.3.1",
"@types/jasmine": "2.5.38",
"@types/node": "^6.0.42",
"angular-cli": "1.0.0-beta.24",
"aws-sdk": "^2.49.0",
"bcryptjs": "^2.3.0",
"body-parser": "~1.15.2",
"connect-multiparty": "^2.0.0",
"cookie-parser": "~1.4.3",
"core-js": "^2.4.1",
"cors": "^2.8.3",
"debug": "~2.2.0",
"express": "~4.14.0",
"express-fileupload": "^0.1.3",
"express-session": "^1.15.2",
"hbs": "~4.0.1",
"imgix-core-js": "^1.0.5",
"jsonwebtoken": "^5.7.0",
"mongoose": "^4.4.12",
"mongoose-unique-validator": "^1.0.2",
"morgan": "~1.7.0",
"multer": "^1.3.0",
"multer-s3": "^2.7.0",
"nodemailer": "^4.0.1",
"rxjs": "^5.0.1",
"s3fs": "^2.5.0",
"serve-favicon": "~2.3.0",
"ts-helpers": "^1.1.1",
"typescript": "~2.0.3",
"uuid": "^3.0.1",
"zone.js": "^0.7.2"
},
"devDependencies": {
"codelyzer": "~2.0.0-beta.1",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "~4.0.13",
"ts-node": "1.2.1",
"tslint": "^4.0.2"
}
}
答案 0 :(得分:0)
诀窍在package.json中,改变了:
"start": "http-server dist/",
到
"start": "node server.js",
我在本地使用了另一个package.json。