向我的 Node 服务器发送 AJAX 请求 - 未通过

标签 ajax node.js express https

我目前正在将流量重定向到我的 Node 服务器上的 https:

var express = require('express');
var path = require('path');

var app = express();
var port = process.env.PORT || 8080;
app.set('port', port);
app.use(express.static(path.join(__dirname, './src/public')));

app.all('*', function(req, res, next) {
  if(req.headers["x-forwarded-proto"] === "https"){
    // OK, continue
    return next();
  };
  res.redirect('https://'+req.hostname+req.url);
})

app.get('*', function( req, res ) {
  res.sendFile(path.join(__dirname, './src/public/index.html'));
} );

app.use(require('./server/routes/index'));

app.listen(process.env.PORT || 8080, function (){
    console.log('Express started on port ' + app.get('port') + '; press Ctrl-C to terminate.');
  });

module.exports = app;

这样做时,我的 AJAX 调用无法通过:net::ERR_CONNECTION_REFUSED。当然,当我删除上述重定向时,我的 AJAX 调用就会通过。

我设法从遇到此问题的人那里找到了另一篇关于 SO 的帖子,但建议是设置 Access-Control-Allow-Origin 来接受任何传入的 AJAX 请求,这似乎是一个安全问题。

如果我想继续使用 https 重定向,有没有办法允许 AJAX 调用通过,或者我需要关闭重定向吗?

最佳答案

使用req.protocalreq.get('host')获取协议(protocol)和主机url

 app.all('*', function(req, res, next) {
      if(req.headers["x-forwarded-proto"] === "https"){
        // OK, continue
        return next();
      };
      res.redirect(req.protocol + '://' + req.get('host') + req.originalUrl);
    })

关于向我的 Node 服务器发送 AJAX 请求 - 未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413440/

相关文章:

node.js - 无法在 "modelRepository"构造函数的位置 #0 注入(inject)依赖项 "GetModelService"。原因 : Cannot read property 'name' of undefined

php - Ajax 未在实时服务器上加载帖子,但在本地主机上运行

javascript - 如何在ajax回调上选择 radio 输入

php - Ajax 方法显示错误的输入

node.js - 如何使用 npm 脚本将自定义提交消息推送到 github?

node.js - Nodejs - 带有 vhost 的动态快速子域

node.js - NodeJS : can not emit event "Object ...{} has no method ' emit'

.net - 带有 json 对象的 ajax post 中的 antiforgerytoken ASP.NET MVC

javascript - Node - 将 m3u8 流保存为 mp3 文件

node.js - Node/Express - 静态服务不工作/如何将路由与静态服务文件一起使用