我正在制作一个包含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
})
})
})
您在客户端应用程序中调用的fetch()
函数允许您从node.js API获取信息。但是,它不允许您重定向到另一个页面。
如果要重定向,可以使用html元素指向Express服务器的URL,在这里可以将您重定向到另一页。
服务器代码:
app.get('/redirect-me', (req, res) => {
res.redirect(307, 'https://google.com') //nothing happens, google.com as an example
res.render('home')
})
客户端代码(html):
<a href="/redirect-me">Click here and you will be redirected to Google</a>