1. 安装axios: npm install --save axios
2. 安装 @nuxtjs/axios和@nuxtjs/proxy来处理 axios 跨域问题: npm i @nuxtjs/axios @nuxtjs/proxy -D
3. nuxt.config.js中配置:
modules: ['@nuxtjs/axios', "@nuxtjs/proxy"],
axios: {
retry: { retries: 3 },
//开发模式下开启debug
debug: process.env._ENV == "production" ? false : true,
//设置不同环境的请求地址
baseURL:
process.env._ENV == "production"
? "http://localhost:3000/api"
: "http://localhost:3000/api",
withCredentials: true,
headers: { 'Content-Type': 'application/json', 'crossDomain': true },
timeout: 5000,
},
proxy: {
'/api/': {
target: 'http://192.168.1.53:3009/',
pathRewrite: {
'^/api/': ''
}
}
}
4. 使用:
async login({ commit }, { username, Pwd }) {
try {
const { data } = await axios.post('/API/User/Login', { username, Pwd })
console.log('apidata:', data)
commit('SET_USER', data)
} catch (error) {
if (error.response && error.response.status === 401) {
throw new Error('Bad credentials')
}
console.log(error)
throw error
}
},