Я столкнулся с проблемой, когда попытался сделать производственную сборку моего проекта angular и node.js.Когда я запускаю свой угловой проект с командой ng serve
, а бэкэнд с nodemon server
, все работает нормально.Но когда я делаю ng build --prod
и изменяю свой бэкэнд, чтобы выбрать статику из "dist".Я не получаю полную функциональность приложения, у меня обычно есть страница регистрации и страница входа, но есть проблема со страницей профиля.На этой странице должна отображаться личная информация пользователя, но в день ответа с сервера я получаю пустое тело и статус 200 ОК.Ниже я цитирую выдержки из моего кода и скриншоты инспектора.Помогите пожалуйста разобраться в чем проблема.Буду признателен за любые советы.
sevice:
import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {User} from './user';
@Injectable()
export class MntApiService {
private data: any = [];
private mntAPI = 'http://localhost:3000';
constructor( private _http: HttpClient ) {
}
getUsers(): Observable<any> {
return this._http.get<any>( this.mntAPI + '/users' );
}
addUser( user: User ): Observable<any> {
return this._http.post<any>( this.mntAPI + '/signup', user );
}
addEditUser( id, user: User ): Observable<any> {
return this._http.post<any>( this.mntAPI + '/profile/' + id, user );
}
getById( id: string ): Observable<any> {
return this._http.get( this.mntAPI + '/profile/' + id, {responseType: 'json'} )
.do( data => {
this.data = data;
console.log( data );
} )
.catch( this.handleError );
}
private handleError( err: HttpErrorResponse ) {
console.log( err );
return Observable.throw( err.message );
}
}
компонент:
import {Component, OnInit} from '@angular/core';
import {MntApiService} from '../mnt-api.service';
import * as jwt_decode from 'jwt-decode';
@Component( {
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: [ './user-profile.component.scss' ]
} )
export class UserProfileComponent implements OnInit {
public data: {
user: [
{
email?: string;
password?: string;
first_name?: string;
last_name?: string;
phone_number?: string;
smartkontract_id?: string;
country?: string;
city?: string;
}
]
};
private token: string = localStorage.getItem( 'id_token' );
private tokenPayload: any = jwt_decode( this.token ) || null;
private id = this.tokenPayload.userId;
constructor( private mntApiService: MntApiService ) {
}
ngOnInit() {
this.getUser( this.id );
}
getUser( id ) {
this.mntApiService.getById( id )
.subscribe( users => {
this.data = users;
} );
}
}
файл node.js users.js
router.get('/profile/:id', (req, res) => {
const id = req.params.id;
console.log(id);
let sql = 'SELECT * FROM users WHERE id = ?';
config.query(sql, id, (err, user) => {
console.log(user);
if (err) {
res.status(500).json({
message: err
});
return;
} else {
res.status(200).json({
user: user
});
}
});
});
my package.json
"dependencies": {
"@angular/animations": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",
"@angular/router": "^5.2.0",
"@auth0/angular-jwt": "^2.0.0",
"@nguniversal/express-engine": "^6.0.0",
"@types/jwt-decode": "^2.2.1",
"@types/moment": "^2.13.0",
"bcrypt": "^2.0.0",
"body-parser": "^1.18.2",
"bootstrap": "^4.0.0",
"core-js": "^2.4.1",
"dotenv": "^5.0.1",
"express": "^4.16.3",
"font-awesome": "^4.7.0",
"jquery": "^3.3.1",
"jsonwebtoken": "^8.2.1",
"jwt-decode": "^2.2.0",
"moment": "^2.22.1",
"morgan": "^1.9.0",
"mysql": "^2.15.0",
"ngx-slick": "^0.1.3",
"node-mysql": "^0.4.2",
"rxjs": "^6.1.0",
"rxjs-compat": "^6.1.0",
"script-loader": "^0.7.2",
"slick-carousel": "^1.8.1",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular/cli": "~1.7.2",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"nodemon": "^1.17.3",
"protractor": "~5.1.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3"
}
}
app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');
const usersRoutes = require('./api/routes/users');
app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res ) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.Header('Content-Type', 'application/json');
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.Header('Content-Type', 'application/json');
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
app.use('/', usersRoutes);
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
});
app.use((error, req, res, next) => {
console.log(error);
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
module.exports = app;
и снимки экрана:
введите описание изображения здесь
введите описание изображения здесь
введите описание изображения здесь