axios请求mysql_如果axios请求失败,如何获取后端接口返回的状态码及错误信息

这两天在工作中遇到一个问题,一个请求返回400错误,我需要向用户展示后端返回的错误信息,但是用普通的catch方法只能获取到浏览器返回的400错误提示,不能获取到后端返回的,后经查阅得出下面方法:

axios.get('/user/12345')

.catch(function (error) {

if (error.response) {

// The request was made and the server responded with a status code

// that falls out of the range of 2xx

console.log(error.response.data);

console.log(error.response.status);

console.log(error.response.headers);

} else if (error.request) {

// The request was made but no response was received

// `error.request` is an instance of XMLHttpRequest in the browser and an instance of

// http.ClientRequest in node.js

console.log(error.request);

} else {

// Something happened in setting up the request that triggered an Error

console.log('Error', error.me

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为你提供一个Vue和Node.js配合MySQL的简单项目示例,包括登录功能和记事本功能。 1. 创建数据库和表 首先需要创建一个MySQL数据库和表,用于存储用户信息和记事本内容。 ``` CREATE DATABASE myapp; USE myapp; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(50) NOT NULL ); CREATE TABLE notes ( id INT AUTO_INCREMENT PRIMARY KEY, userId INT NOT NULL, content TEXT NOT NULL, createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (userId) REFERENCES users(id) ); ``` 以上代码创建了一个名为“myapp”的数据库,包含两个表:“users”表用于存储用户信息,包括ID、用户名和密码;“notes”表用于存储记事本内容,包括ID、用户ID、内容和创建时间。 2. 创建Node.js后端API 在新建一个文件夹,用于存放Node.js项目文件,例如“myapp”。 在该文件夹下,创建一个名为“package.json”的文件,用于存放项目依赖和配置信息。在命令行中输入以下命令,按照提示填写项目信息: ``` npm init ``` 在“myapp”文件夹下,创建一个名为“server.js”的文件,用于编写Node.js后端API代码。在该文件中,需要引入Express、body-parser和MySQL模块,分别用于构建HTTP服务、解析请求体和连接MySQL数据库。 ``` const express = require('express'); const bodyParser = require('body-parser'); const mysql = require('mysql'); const app = express(); const port = 3000; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'myapp' }); connection.connect(); app.post('/api/login', (req, res) => { const username = req.body.username; const password = req.body.password; connection.query(`SELECT * FROM users WHERE username='${username}' AND password='${password}'`, (error, results, fields) => { if (error) throw error; if (results.length > 0) { res.send({ success: true, message: '登录成功', user: results[0] }); } else { res.send({ success: false, message: '用户名或密码错误' }); } }); }); app.get('/api/notes', (req, res) => { const userId = req.query.userId; connection.query(`SELECT * FROM notes WHERE userId=${userId} ORDER BY createdAt DESC`, (error, results, fields) => { if (error) throw error; res.send(results); }); }); app.post('/api/notes', (req, res) => { const userId = req.body.userId; const content = req.body.content; connection.query(`INSERT INTO notes (userId, content) VALUES (${userId}, '${content}')`, (error, results, fields) => { if (error) throw error; res.send({ success: true, message: '保存成功' }); }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ``` 以上代码创建了一个HTTP服务,包含三个API接口: - “/api/login”用于用户登录,接收用户名和密码,查询数据库中是否存在对应记录,并返回登录结果和用户信息; - “/api/notes”用于获取用户的记事本内容,接收用户ID,查询数据库中对应用户的所有记录,并按照创建时间倒序排列返回; - “/api/notes”用于保存用户的记事本内容,接收用户ID和内容,将记录插入数据库,并返回保存结果。 3. 创建Vue前端界面 在“myapp”文件夹下,创建一个名为“client”的子文件夹,用于存放Vue项目文件。 在命令行中输入以下命令,创建一个基于Webpack模板的Vue项目: ``` vue init webpack client ``` 按照提示填写项目信息,等待依赖安装完成后,进入“client”文件夹,输入以下命令运行Vue项目: ``` npm run dev ``` 在浏览器中打开http://localhost:8080,应该能看到Vue项目的默认界面。 在“client”文件夹下,进入“src/components”子文件夹,创建一个名为“Login.vue”的文件,用于编写用户登录界面。在该文件中,需要引入axios模块,用于发送HTTP请求。 ``` <template> <div> <h1>用户登录</h1> <form> <div> <label>用户名:</label> <input type="text" v-model="username"> </div> <div> <label>密码:</label> <input type="password" v-model="password"> </div> <div> <button type="button" @click="login">登录</button> </div> </form> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '' }; }, methods: { login() { axios.post('/api/login', { username: this.username, password: this.password }).then(response => { if (response.data.success) { this.$emit('login', response.data.user); } else { alert(response.data.message); } }).catch(error => { console.error(error); }); } } }; </script> ``` 以上代码创建了一个包含用户名、密码输入框和登录按钮的用户登录界面。当用户点击登录按钮时,会向后端发送一个“/api/login”接口的POST请求,传递用户名和密码参数,并根据返回结果执行相应的操作。 在“client”文件夹下,进入“src/components”子文件夹,创建一个名为“Notebook.vue”的文件,用于编写记事本界面。在该文件中,需要引入axios模块,用于发送HTTP请求。 ``` <template> <div> <h1>记事本</h1> <form> <div> <textarea v-model="content"></textarea> </div> <div> <button type="button" @click="save">保存</button> </div> </form> <ul> <li v-for="note in notes" :key="note.id">{{ note.content }}</li> </ul> </div> </template> <script> import axios from 'axios'; export default { props: { user: { type: Object, required: true } }, data() { return { content: '', notes: [] }; }, created() { this.loadNotes(); }, methods: { loadNotes() { axios.get(`/api/notes?userId=${this.user.id}`).then(response => { this.notes = response.data; }).catch(error => { console.error(error); }); }, save() { axios.post('/api/notes', { userId: this.user.id, content: this.content }).then(response => { if (response.data.success) { this.loadNotes(); this.content = ''; } else { alert(response.data.message); } }).catch(error => { console.error(error); }); } } }; </script> ``` 以上代码创建了一个包含文本输入框、保存按钮和记事本列表的记事本界面。当用户点击保存按钮时,会向后端发送一个“/api/notes”接口的POST请求,传递用户ID和内容参数,并根据返回结果执行相应的操作。同时,页面会重新加载并显示更新后的记事本列表。 4. 创建Vue根组件 在“client”文件夹下,进入“src”子文件夹,打开“App.vue”文件,用于编写整个Vue项目的根组件。在该文件中,需要引入Login和Notebook组件,根据用户登录状态切换显示。 ``` <template> <div> <login v-if="!user" @login="user = $event"></login> <notebook v-if="user" :user="user"></notebook> </div> </template> <script> import Login from './components/Login.vue'; import Notebook from './components/Notebook.vue'; export default { components: { Login, Notebook }, data() { return { user: null }; } }; </script> ``` 以上代码根据用户登录状态切换显示Login和Notebook组件,并将用户信息通过props传递给Notebook组件。 5. 编译和运行Vue项目 在命令行中进入“client”文件夹,输入以下命令编译Vue项目: ``` npm run build ``` 编译完成后,在“client/dist”子文件夹下会生成一个名为“index.html”的文件和一些静态资源文件。 在“myapp”文件夹下,修改“server.js”文件,添加以下代码,用于引入Vue项目的静态资源: ``` app.use(express.static(__dirname + '/client/dist')); ``` 在命令行中输入以下命令运行Node.js后端API服务: ``` node server.js ``` 在浏览器中访问http://localhost:3000,应该能看到Vue项目的登录界面。输入正确的用户名和密码后,应该能进入记事本界面,进行内容输入和保存操作。 以上就是一个使用Vue和Node.js配合MySQL的简单项目示例,包括登录功能和记事本功能。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值