【问题标题】:Angular image not served properly from nodejs backend角度图像未从 nodejs 后端正确提供
【发布时间】:2021-06-24 19:54:53
【问题描述】:

我想从我的 nodejs 后端提供一个图像并将其显示在前端,我的后端运行在 8081 端口,前端运行在 8080。我可以在 http://localhost:8081/image.JPG 中看到图像,但在前端我我正在寻找 404,因为它正在寻找 http://localhost:8081/image.JPG。

var express = require('express');
var cors = require("cors");
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 
global.__basedir = __dirname;
app.use(express.static(__dirname + '/resources/static/assets/uploads/'));
app.use(function (req, res, next) {


  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');


  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});
 
const db = require('./app/config/db.config');

app.use(cors({origin: 'http://localhost:8080'}));
  
// force: true will drop the table if it already exists
db.sequelize.sync({force: false}).then(() => {
  console.log('Drop and Resync with { force: false }');
}); 

require('./app/routers/upload.router.js')(app);
 
// Create a Server
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port)
 
})

我在浏览器中查询时可以看到图像,因为它正在寻找 8081 端口

前端正在寻找端口 8080,因此出现以下错误--

有人请给我一个解决方案。我没有任何线索。谢谢。

【问题讨论】:

  • 您只需使用像 htttp://example.com/image.jpg 这样的完整路径,而不仅仅是 /image.jpg。如果主机名和端口都不相同,则就像它是不同的服务器。

标签: node.js angular frontend


【解决方案1】:

您可以采取的一种方法是使用 Angular 提供的代理配置,如下所示:

{
  "/api/assets": {
    "target": "http://localhost:8081",
    "secure": false
  }
}

现在,当您在前端点击此 URL 时:http://localhost:8080/api/assets/image.JPG 它将代理到 http://localhost:8081/api/assets/image.JPG

你的图片标签看起来像<img src="/api/assets/image.JPG">

更多关于代理配置和如何配置:https://angular.io/guide/build#proxying-to-a-backend-server

【讨论】:

  • 但是 img src 来自后端,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-26
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
相关资源
最近更新 更多