提问者:小点点

无法使用Express和EJS从POST请求重定向


我正在制作一个包含Node.js、Express和EJS的应用程序,在按下一个按钮后,它会将您重定向到一个不同的页面(例如从localhost:3000/转到localhost:3000/about)。post请求被服务器接收,因为'post request'被记录到服务器端控制台,但是我没有被重定向,没有错误消息或任何东西。

服务器:

const express = require('express')
const app = express()
app.listen(3000)
app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => { //works as intended
    res.render('home')
})

app.post('/', (req, res) => { 
   res.redirect(307, 'https://google.com') //nothing happens, google.com as an example
   console.log('post request') //logged on server console
})

客户:

button = document.getElementById('button')
text = document.querySelector('textarea')
button.addEventListener('click', () => {
    fetch('/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            data: text.value
        })
    })
})

共1个答案