当我用javascript文件打开相关页面时,我得到了net::ERR_CONNECTION_REFUSED错误。我正在使用node.js作为服务器,我正在为我的静态页面编写一个javascript文件中的post请求。service_provider.js是我的javascript文件,用于为我的静态页面(Html)编写javascript函数。 node.js 是我的node.js服务器文件。
service_provider.js
function getJourneyAnalize(
_fonkSuccess,
_fonkBefore,
_fonkError,
_deviceId,
_driverId,
_dateStart,
_dateEnd,
_timeStart,
_timeEnd,
_map,
_kmStart,
_kmEnd
) {
var _fromBody = {
device_id: _deviceId,
driver_id: _driverId,
date_start: _dateStart,
date_end: _dateEnd,
time_start: _timeStart,
time_end: _timeEnd,
map: _map,
km_start: _kmStart,
km_end: _kmEnd
};
$.ajax({
type: 'POST',
url: apiUrl + '/ReportFms/JourneyAnalize',
data: JSON.stringify(_fromBody),
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf-8',
beforeSend: function (xhr, settings) {
_fonkBefore();
xhr.setRequestHeader('Authorization', 'Bearer ' + currentUser.access_token);
},
success: _fonkSuccess,
error: _fonkError
});
}node.js
const express = require('express');
const app = express();
var path = require('path');
app.use(
function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
}
)
app.use('/node_modules/jquery/dist', express.static(path.join(__dirname, '../node_modules/jquery/dist')))
app.get('/static-pages/journey-analize-report', function (req, res) {
res.sendFile(path.join(__dirname + '/../static-pages/journey-analize-report/index.html'))
})
app.listen(8000, () => {
console.log('server started');
})发布于 2022-02-19 16:23:45
静态页面显示正确吗?
1-如果静态页位于父文件夹中,则清除第一个斜杠。
res.sendFile(path.join(__dirname + '../static-pages/journey-analize-report/index.html'))2-要在静态文件中提供jquery脚本,可以定义一个个性化路径来代替node_module文件夹
取代:
app.use('/node_modules/jquery/dist', express.static(path.join(__dirname, '../node_modules/jquery/dist')))使用
app.use('/js', express.static(path.join(__dirname, '../node_modules/jquery/dist')))在html文件中,需要带有个性化路径的jquery。
<script src="/js/jquery.min.js"></script>3-如果仍然存在错误,请在静态页面中注释app.use函数和jquery脚本。重新加载服务器以查看其工作是否正常
https://stackoverflow.com/questions/71169114
复制相似问题