【发布时间】: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。如果主机名和端口都不相同,则就像它是不同的服务器。