如何从端口 3000 上的 Nodejs 后端连同数据一起重定向到端口 8080 上的 vuejs 前端 运行

How to redirect to a vuejs front-end running on port 8080 from Nodejs backend on port 3000 along with data

我可以使用

重定向
res.writeHead(302, {
    Location: 'http://localhost:8080/path'
})

但是我需要在重定向的同时发送一些数据。我该怎么做?

我认为 listen() 方法是 nodejs 后端服务器所需要的。

var http = require('http'); 
var url = require('url'); 

http.createServer(function (req, res) { 
 console.log("Request: " + req.method + " to " + req.url); 
 res.writeHead(200, "OK"); 
 res.write("<h1>Hello</h1>Node.js is listening new port"); 
 res.end(); 
}).listen(3000); 

话题:Changing Node.js listening port

从重定向传递数据的一种方法是将其作为查询参数,例如

res.writeHead(302, {
    Location: 'http://localhost:8080/path?data=1'
})

在您的 vue 应用程序上,您可以通过以下方式获取查询参数:

this.$route.query.data

请记住,如果您要传递敏感数据,这是不安全的,不建议这样做。

编辑:

如果符合您的需要,您也可以将数据作为路径参数传递,例如您有这样的 vue 路由:

routes: [
    {
      path: '/path/:data',
      name: 'path',
      component: PathPage,
    },
]

您可以像这样从您的 Express 应用重定向:

res.writeHead(302, {
    Location: 'http://localhost:8080/path/50'
})

您可以像这样从 vue 组件获取参数:

this.$route.params.data // 50