【问题标题】:Redirection to another url is not working after the deployment部署后重定向到另一个 url 不起作用
【发布时间】:2021-07-19 21:06:18
【问题描述】:

const express = require('express')
const app = express()
var open = require('open')

app.get('/', (req, res) => {
    res.send('Hello World!')
    open('https://google.com');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(Example app listening at http://localhost:${PORT})
});

使用上面的代码。部署后我无法重定向到 google.com 并且它在 localhost 中工作

测试网址:https://redirecttestok.herokuapp.com/

请帮助我解决此问题或帮助我使用替代包。

【问题讨论】:

  • 不是在 Express 中重定向请求的方式。

标签: node.js express


【解决方案1】:

这不是如何在 Express 中重定向 - 改用它;

res.redirect(301, 'https://google.com');

编辑:你不能先做res.send。您只能响应一次请求。完整的结果:

const express = require('express');
const app = express();
var open = require('open');

app.get('/', (req, res) => {
    res.redirect(301, 'https://google.com');
});

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
    console.log(`Example app listening at http://localhost:${PORT}`);
});

【讨论】:

  • 不,它不工作。 error 错误 [ERR_HTTP_HEADERS_SENT]: 发送到客户端后无法设置标头
  • const time = () => { for(time in times) { if(Date.now() > times[time].time) { open(times[time]..url); } } } 做这样的 res.redirect 也不会起作用,这就是我使用 open 的原因。请帮忙
  • 知道了,但在这种情况下是什么 const time = () => { for(time in times) { if(Date.now() > times[time].time) { open(times[时间]..url); } } } 在这种情况下,我想为这个特定的 url 打开一个新标签
  • 我不认为您可以发送多个页面作为对单个请求的响应。在前端处理它并发送格式化数据 - 例如 json。
  • 不“打开”只是在您的机器上本地打开选项卡,这意味着它不会在您的实时环境中工作?要发送多个响应,请使用 res.write 和 res.end,但我认为您不能触发多选项卡行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多