vue2项目中,点击提交按钮后,发送重定向请求给服务器获的新页面,用axios
根据参考资料中的axios代码,可以尝试以下步骤来实现在vue2项目中点击提交按钮后用axios向服务器发送重定向请求并在新页面中显示结果:
import axios from 'axios'
handleSubmit() {
axios({
method: 'post',
url: '/api/redirect',
data: {
name: this.name,
password: this.password
},
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then((response) => {
// 获取服务器返回的重定向 URL
const redirectUrl = response.data.redirectUrl
// 在当前窗口打开重定向 URL
window.location.href = redirectUrl
}).catch((error) => {
console.error(error)
})
}
其中,URL /api/redirect
是服务器重定向接口的路径,name
和 password
是表单数据。
请求头中的 Content-Type
表示请求体数据类型为 JSON 格式。
withCredentials
表示发起跨域请求时是否携带身份信息(例如 cookie),需要服务端支持。
该请求成功后,会返回一个包含重定向 URL 的响应体。
router.post('/redirect', (req, res) => {
const name = req.body.name
const password = req.body.password
// 处理表单数据...
const redirectUrl = 'http://www.example.com' // 重定向 URL
// 返回包含重定向 URL 的响应体
res.json({
redirectUrl: redirectUrl
})
})
其中,router
是 Express 路由器实例,/redirect
是接口路径。
在接口代码中,需要使用 body-parser 中间件来解析请求体数据。具体操作方式可以参考如下示例:
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
以上步骤实现了在vue2项目中点击提交按钮后用axios向服务器发送重定向请求并在新页面中显示结果。其中,需要根据实际应用场景进行具体的定制化开发。