簡體   English   中英

ExpressJS: res.redirect() 不起作用。 如何在單頁應用程序中重定向?

[英]ExpressJS: res.redirect() does not work. How to redirect in single page app?

問題:

我有一個 static 單頁應用程序,在其中我按下提交輸入,該輸入使用 Axios 從 Vue 組件向 Express 服務器發送 POST 請求,在該服務器中我處理 POST 並嘗試重定向到另一個頁面,但是res.redirect("/home")和/或res.sendFile(path.join(__dirname, "../dist/index.html")); 不要重定向。

預期行為:

我想在提交后重定向到/home 其他一切都很好。

服務器文件:

const history = require('connect-history-api-fallback');
const path = require("path");

// serve the Vue Interface
const buildLocation = path.join(__dirname, "../dist");
app.use(express.static(buildLocation));
app.use(history({
  disableDotRule: true,
  verbose: true
}));
app.use(express.static(buildLocation));

app.get('/home', function(req, res) {
  res.sendFile(path.join(__dirname, "../dist/index.html"));
});


app.post("/dhcpIP", function (req, res) {
  // check if request body is empty
  if (req.body.constructor === Object && Object.keys(req.body).length === 0)
    return;
  // doing things that work
  res.redirect('/'); // this doesn't work
});

const http_server = http.createServer(app);

http_server.listen(http_port);

我構建了 Vue CLI 應用程序,以便獲得dist文件夾。 dist文件夾中,我有一個index.html包含整個應用程序。

發送 POST 請求的 Vue 組件:

<template>
  <form action="javascript:void(0);" @submit="sendData" novalidate="true">
    <input type="text"/>
    <input type="password"/>
    <input type="submit"/>
  </form>
</template>

<script>
import axios from "axios";

const serverURL = location.origin;
const server = axios.create({ baseURL: serverURL });

export default {
  name: "DHCP",
  data() {
    return {
      visible: false,
      ssid: "",
      password: ""
    };
  },
  methods: {
    sendData: function() {
      if (this.ssid === "" || this.password === "") return;
      let currentUrl = window.location.pathname;
      console.log("currentUrl:");
      console.log(currentUrl);
      server
        .post(currentUrl, { ssid: this.ssid, password: this.password })
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

路由器文件

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
    component: Home,
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
  },
  {
    path: "/dhcpIP",
    name: "DHCP",
    component: () => import(/* webpackChunkName: "dhcpIP" */ "../views/DHCP.vue")
  },
];

const router = new VueRouter({
  mode: "history",
  // base: process.env.BASE_URL,
  routes,
});

export default router;

我嘗試編寫盡可能少的代碼。

在您的發布路線中,您已經返回了一些東西

app.post("/dhcpIP", function (req, res) {
  // check if request body is empty
  if (req.body.constructor === Object && Object.keys(req.body).length === 0)
    return;
  // doing things that work
  res.redirect('/'); // this doesn't work
});

return 語句結束 function 執行。 話雖這么說:您正在返回“一些有效的東西”,然后使用res.redirect方法,該方法被忽略,因為function 已經返回了 value

改用router.push() ,因為您不是重定向,而是使用路由器

https://router.vuejs.org/guide/essentials/navigation.html

如果您想要通過重定向離開 SPA,那么您可以根據服務器響應更改 window.location,在這種情況下,從服務器發送 301 或 302,並添加 axios 攔截器它。

https://simplecheatsheet.com/axios-interceptors/

我已經使用這個 SO 線程解決了問題。 顯然,如果您正在執行 AXIOS 帖子,則無法從 Express 服務器重定向,您必須在 AXIOS 方法中處理重定向。
我還沒有找到關於這個主題的任何解釋或文檔。 當我這樣做時,我會更新這個答案。

我是這樣做的:

服務器文件:

app.post("/dhcpIP", function (req, res) {
  // check if request body is empty
  if (req.body.constructor === Object && Object.keys(req.body).length === 0)
    return;
  // doing things that work

  if(errors.length != 0) {
    res.sendStatus(500);
  } else
  res.sendStatus(200);
});

Vue組件:

    sendData: function() {
      if (this.ssid === "" || this.password === "") return;
      let currentUrl = window.location.pathname;
      server
        .post(currentUrl, { ssid: this.ssid, password: this.password })
        .then(res => {
          if(res.status == 200) {
            alert("Settings have been saved.");
            window.location = currentUrl;
          } else {
            alert("Something went wrong. Please try again");
          }
        })
        .catch(err => {
          console.log(err);
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM