首页 > 解决方案 > 如何更改 'app.use(express.static(path.join(__dirname, 'public')));' 服务请求以 '/api/' 结尾

问题描述

我正在尝试部署我的 Angular + NodeJS 应用程序。我正在尝试在 nginix 上使用反向代理来获取/api/如下位置/etc/nginx/nginx.conf

        location /api/ {
           proxy_pass http://95.216.132.229:3000;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_cache_bypass $http_upgrade;
}

app.js文件中:

app.use(express.static(path.join(__dirname, '/api/public')));

http://95.216.132.229/api/images/static/footer.jpeg在我的 Angular html 文件中使用地址来访问图像文件,但我得到:

GET http://95.216.132.229/api/images/static/footer.jpeg 404 (Not Found)错误!

我该如何解决?

编辑:

这是app.js文件:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var strategyRouter = require ('./routes/strategy');
var newsRouter = require('./routes/news');
var uploadRouter = require('./routes/upload');
var digitalCurrency = require('./routes/digitalcurrency');

var config = require('./config');
var app = express();

var dbURL = config.strategyURL;
var connect = mongoose.connect(dbURL);

//var connect2 = mongoose.connect(config.priceDataURL).then((db) => console.log('Connecting correctly to the priceDataURL'));
connect.then((db) => console.log('Connecting correctly to the server',db.connections[0].collections ) , (err) => {console.log('errrrrr',err)});
var dbConnect = require('./dbConnection');

//var connect2 = mongoose.connect(config.priceDataURL).then((db) => console.log('Connecting correctly to the priceDataURL'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(passport.initialize());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/api/public')));

app.use('/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/strategies' , strategyRouter);
app.use('/api/news' , newsRouter);
app.use('/api/upload', uploadRouter);
app.use('/api/currency', digitalCurrency);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

这是header.component.ts

import { Component, OnInit , OnDestroy, OnChanges, HostListener} from '@angular/core';
import {MatDialog, MAT_DIALOG_DATA} from '@angular/material/dialog';
import{SignupComponent} from 'src/app/signup/signup.component';
import { LoginComponent } from '../login/login.component';
import{AuthService} from '../services/auth.service';
import { Subscription } from 'rxjs';
import{ProfileManagmentService} from '../services/profile-managment.service';
import { baseurl } from '../shared/baseurl';
import{ Router, NavigationEnd } from '@angular/router';
import{ TranslocoService } from "@ngneat/transloco";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit , OnChanges{

  profileVisibility : boolean = false;
  username : string;
  userNameSubscription : Subscription;
  visibilitySubscription : Subscription;
  imageSubscription : Subscription;
  mySubscription : Subscription;
  imageAddress : string = baseurl + 'images/static/' + 'profileDefualt.png';
  logoImageAddress : string = baseurl + 'images/static/Logo1.png';
  address : string = baseurl + 'images/static/';
  avatar : number;
  name : string;
  flag : number;

  @HostListener('window:resize', ['$event'])
  getScreenSize(event?) {
        this.avatar  = window.innerWidth * 0.04;
        this.flag = window.innerWidth * 0.015;
        //this.resize();
  }
  

  constructor(public dialog : MatDialog, private authService : AuthService,
    private profileManagmentService : ProfileManagmentService, private router : Router,
    private translocoService : TranslocoService) {
            
      
     }

  ngOnInit() {
    

    this.userNameSubscription = this.authService.getUsername().subscribe((name) => {
      console.log('name from loadcredentials' + name);
      this.username = name;
    });
    this.visibilitySubscription = this.authService.getVisibility()
    .subscribe((visibility) => {
        this.profileVisibility = visibility;
        this.imageSubscription=this.profileManagmentService.getProfileImage().subscribe((image) => {
          if(image.image){
             this.imageAddress = baseurl + 'images/profile/' + image.image;
          }
          else{
            this.imageAddress = baseurl + 'images/static' + 'profileDefualt';
          }
      });
      });
    this.authService.loadUserCredentials();
    if(this.authService.isLoggedIn()){
      this.profileVisibility = true;
    }

    this.profileManagmentService.getUserProfile().subscribe((user) => {
      if(user.firstName && user.lastName){
        this.name = user.firstname+ '' + user.lastname;
      }
      else if(user.username){
        this.name = user.username;
      }
      else{
        this.name="new user"
      }
    });
    this.avatar = window.innerWidth * 0.04;
    this.flag = window.innerWidth * 0.015;
    let lang = this.translocoService.getActiveLang();
    if(lang === "en"){
      this.logoImageAddress =  baseurl + 'images/static/hd-en-logo.jpeg';
    }
    else {
      this.logoImageAddress =  baseurl + 'images/static/hd-fa-logo.jpeg';
    }
  }
  ngOnDestroy(){
    this.userNameSubscription.unsubscribe();
    this.visibilitySubscription.unsubscribe();
    this.imageSubscription.unsubscribe();

  }
  openSignUpDialog(){
    this.dialog.open(SignupComponent, { width : '30vw'});
  }
  openLogInDialog(){
    let loginDialog = this.dialog.open(LoginComponent , {width : '30vw' , data : {username : this.username} });
    loginDialog.afterClosed().subscribe((result) => {
      if(result){
        console.log('result', result);
        this.imageSubscription=this.profileManagmentService.getProfileImage().subscribe((image) => {
          console.log('image.image' , image.image);
          this.imageAddress = baseurl + 'images/profile/' + image.image;
        });
    
      }})
  }
  ngOnChanges(){
    console.log('leave');
  }
  logOut(){
    this.username = undefined;
    this.profileVisibility = false;
    this.imageAddress = undefined;
    this.authService.logOut();
    this.router.navigate(['home']);
  }
  changeLang(lang : string){
    this.translocoService.setActiveLang(lang);
    if(lang === "en"){
      this.logoImageAddress =  baseurl + 'images/static/hd-en-logo.jpeg';
    }
    else {
      this.logoImageAddress =  baseurl + 'images/static/hd-fa-logo.jpeg';
    }
  }
}

并且header.component.html

<mat-toolbar>
  <mat-toolbar-row class="whiteToolbar">
    <div style="display: flex;" fxLayout="row" fxLayoutAlign="space-around center" fxLayoutGap="15vw">
      <div fxFlex  >
        <!--avatar-->
        <div style="display: flex;" fxLayout="row" fxLayoutAlign="space-around center" fxLayoutGap="0.1vw"
        >
          <a  routerLinkActive [matMenuTriggerFor]="menu"  *ngIf="profileVisibility">
            <ngx-avatar src="{{imageAddress}}" [round]="true" [size]="avatar" ></ngx-avatar>
          </a>
          <a  *ngIf="!profileVisibility" >
            <ngx-avatar src="{{imageAddress}}" [round]="true" [size]="avatar" ></ngx-avatar>
          </a>
          <a class="avatar" [matMenuTriggerFor]="menu"><mat-icon >keyboard_arrow_down</mat-icon></a> 
          <mat-menu  #menu="matMenu" >
            <button mat-menu-item routerLink="/usersProfile" >{{'userProfile' | transloco}}</button>
            <button mat-menu-item (click)="logOut()" >{{'logout' | transloco}}</button>
          </mat-menu>
          <!--username and notif and alarm-->
          <div style="display: flex;" fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="0.01vw"
          *ngIf="profileVisibility">
            <p >{{name}}</p>
            <div style="display: flex;" fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="0.1vw">
              <button class="headerButton" mat-icon-button >
                <mat-icon>notifications</mat-icon>
              </button>
              <button class="headerButton" mat-icon-button >
                <mat-icon>mail</mat-icon>
              </button>
            </div>
          </div>
          <!--login - signUp-->
          <div style="display: flex;" fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="0.2vw"
          *ngIf="!profileVisibility">
            <a class="loginButton" (click)="openLogInDialog()" *ngIf="!profileVisibility" >
              {{'login' | transloco}}</a>
            <a class="signupButton" (click)="openSignUpDialog()" *ngIf="!profileVisibility">
              {{'signup' | transloco}}</a>  
          </div>
        </div>
    </div>
    <!--flags-->
    <div fxFlex>
      <div style="display: flex;" fxLayout="column" fxLayoutAlign="end end" fxLayoutGap="0.1vw">
        <div style="display: flex;" fxLayout="row" fxLayoutAlign="end center" fxLayoutGap="1vw">
          <a (click)="changeLang('fa')">فارسی</a>
          <a>
            <ngx-avatar src="{{address+ 'iran.png'}}" [round]="true" [size]="flag"
            (click)="changeLang('fa')" ></ngx-avatar>
          </a>
        </div>
        <div style="display: flex;" fxLayout="row" fxLayoutAlign="end center" fxLayoutGap="1vw">
          <a (click)="changeLang('en')">English</a>
          <a>
            <ngx-avatar src="{{address+ 'uk.png'}}" [round]="true" [size]="flag" 
            (click)="changeLang('en')"></ngx-avatar>       
          </a>
        </div>
      </div>     
    </div>
    <!--Make profit here-->
    <div class="makeProfit">
      <div style="display: flex;" fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="3vw">
        <mat-icon>arrow_left</mat-icon>
        <a>{{'makeProfit' | transloco}}</a>
      </div>
    </div>

  </div>
    <span class="example-spacer"></span>
  
      <img src={{logoImageAddress}} 
      class="example-logo">
  
  </mat-toolbar-row>
  <!--blueToolbar-->
  <mat-toolbar-row class="blueToolbar" dir="rtl">
      <div style="display: flex;" fxLayout="row" fxLayoutAlign="space-around center" fxLayoutGap="1.7vw">
        <!--buildRobot-->
        <div fxFlex fxFlexOffset="5" >
          <div style="display: flex;" routerLink="/strategy" class="headerItems" fxLayout="column" 
          fxLayoutAlign="center center" fxLayoutGap="0.01vw" routerLinkActive="active">
            <!--icon-->
            <img src="{{address + 'wrobot.png'}}" style="width: 2vw; height: 2vw;" >
            <a routerLink="/strategy">{{'buildRobot' | transloco}}</a>
          </div>
        </div>
        <!--arEngine-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw" routerLink="/arEngine" routerLinkActive="active">
            <!--icon-->
            <img  src="{{address + 'wengine.png'}}" style="width: 2vw; height: 2vw;">
            <a routerLink="/arEngine"  >{{'ArtificialIntelligenceEngine' | transloco}}</a>
          </div>
        </div>
        <!--bascket-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw" routerLink="/portfolio" routerLinkActive="active">
            <!--icon-->
            <img src="{{address + 'wbascket.png'}}" style="width: 2vw; height: 2vw;">
            <a routerLink="/portfolio" >{{'smartBascket' | transloco}}</a>
          </div>
        </div>
        <!--shop-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw" routerLink="/shop" routerLinkActive="active" >
            <!--icon-->
            <img src="{{address + 'wbuy.png'}}" style="width: 2vw; height: 2vw;">
            <a  routerLink="/shop">{{'Shop' | transloco}}</a>
          </div>  
        </div>
        <!--digitalCurrency-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw" routerLink="/digitalCurrency" routerLinkActive="active">
            <!--icon-->
            <img src="{{address + 'wbitcoin.png'}}" style="width: 2vw; height: 2vw;">
            <a  routerLink="/digitalCurrency">{{'digitalCurrency' | transloco}}</a>
          </div>
        </div>
        <!--news-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw" routerLink="/news" routerLinkActive="active">
            <!--icon-->
            <img src="{{address + 'wnews.png'}}" style="width: 2vw; height: 2vw;">
            <a routerLink="/news">{{'News' | transloco}} </a>
          </div>
        </div>
        <!--chat-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" 
          fxLayoutGap="0.01vw">
            <!--icon-->
            <img src="{{address + 'wchat.png'}}" style="width: 2vw; height: 2vw;">
            <a  >{{'AnalysisAndDiscussionForum' | transloco}}</a>
          </div>
        </div>
        <!--learning-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="0.01vw">
            <!--icon-->
            <img src="{{address + 'wlearning.png'}}" style="width: 2vw; height: 2vw;">
            <a>{{'training' | transloco}}</a>
          </div>
        </div>
        <!--facilities-->
        <div fxFlex>
          <div style="display: flex;" class="headerItems" fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="0.01vw">
            <!--icon-->
            <img src="{{address + 'wfacilities.png'}}" style="width: 2vw; height: 2vw;">
            <a>{{'facilities' | transloco}}</a>
          </div>
        </div>
      </div>
  </mat-toolbar-row>
</mat-toolbar>

<!--
<mat-toolbar color="primary" dir="rtl">
    <div fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="2%">
      <div fxFlex>
        <img src={{logoImageAddress}} style="width: 200px; height: 100px;margin-right: 50px; margin-top: 10px;">
      </div>
      <div fxFlex >
        <div  fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="20px">
          <div fxFlex class="headerItems">
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'robot.png'}}" style="width: 40px; height: 40px;">
              </div>  
              <div fxFlex>
                <a  routerLink="/strategy"  >{{'buildRobot' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems">
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'engine.png'}}" style="width: 40px; height: 40px;">
              </div>  
              <div fxFlex="100" >
                <a routerLink="/arEngine">{{'ArtificialIntelligenceEngine' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems">
            <div fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'bascket.png'}}" style="width: 40px; height: 40px;">
              </div>  
              <div fxFlex>
                <a routerLink="/portfolio">{{'smartBascket' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems">  
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'buy.png'}}" style="width: 40px; height: 40px;">
              </div>
              <div fxFlex>
                <a  routerLink="/shop">{{'Shop' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems">
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'bitcoin.png'}}" style="width: 40px; height: 40px;">
              </div>
              <div fxFlex>
                <a  routerLink="/digitalCurrency">{{'digitalCurrency' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems">
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'news.png'}}" style="width: 40px; height: 40px;">
              </div>
              <div fxFlex>
                <a routerLink="/news">{{'News' | transloco}} </a>
              </div>
            </div>
          </div>
          
          <div fxFlex class="headerItems">
            <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'chat.png'}}" style="width: 40px; height: 40px;">
              </div>
              <div fxFlex>
                <a  routerLink="/digitalCurrency" >{{'AnalysisAndDiscussionForum' | transloco}}</a>
              </div>
            </div>
          </div>
  
          <div fxFlex class="headerItems" routerLink="/tradingView">
            <div fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="2px">
              <div fxFlex>
                <img src="{{address + 'learning.png'}}" style="width: 40px; height: 40px;">
              </div>  
              <div fxFlex>
                <a>{{'training' | transloco}}</a>
              </div>
            </div>
          </div>
        </div>
    </div>
    
    </div>
  
  <div class="flex-spacer">
  </div>
  <div style="margin-left: auto;">
    <div  fxLayout="row" fxLayoutAlign="start center" fxLayoutGap="5px" dir="ltr">
      
      <div fxFlex  *ngIf="imageAddress">
          <a routerLink="/usersProfile" routerLinkActive>
            <ngx-avatar src="{{imageAddress}}" [round]="true" size="100" ></ngx-avatar>
          </a>
      </div>
      <div fxFlex>
        <div  fxLayout="column" fxLayoutAlign="center center" fxLayoutGap="5px" dir="ltr">
          <div fxFlex>
            <div  fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="5px" dir="ltr">
              <div fxFlex>
                <a mat-flat-button (click)="openSignUpDialog()" *ngIf="!profileVisibility">{{'signup' | transloco}}</a>
              </div>
              <div fxFlex>
                <a mat-flat-button (click)="openLogInDialog()" *ngIf="!profileVisibility" >{{'login' | transloco}}</a>
              </div>
              <div fxFlex>
                <a mat-flat-button (click)="logOut()" *ngIf="profileVisibility" >{{'logout' | transloco}}</a>
              </div>
            </div>
          </div>
          <div fxFlex>
            <div  fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="5px" dir="ltr">
              <div fxFlex>
                <a mat-mini-fab (click)="changeLang('en')" color="primary">en</a>
              </div>
              <div fxFlex>
                <a mat-mini-fab (click)="changeLang('fa')" color="primary">fa</a>
              </div>
            </div>
          </div>
        </div>
      </div>
           
  
    </div>
    
  </div>
  </mat-toolbar>
-->

最后baseurl.ts

export const baseurl ="http://95.216.132.229/api/";

 

标签: node.jsangularnginxlocationreverse-proxy

解决方案


推荐阅读