0
点赞
收藏
分享

微信扫一扫

win10修改远程桌面端口,Windows 10下修改远程桌面端口及服务器关闭445端口的操作指南

Java旺 2024-06-30 阅读 18

axios的基本使用和vue脚手架自带的跨域问题解决

1. axios

1.1 导入axios

npm i axios

1.2 创建serve1.js

serve1.js

const express = require('express')
const app = express()

app.use((request,response,next)=>{
	console.log('有人请求服务器1了');
	console.log('请求来自于',request.get('Host'));
	console.log('请求的地址',request.url);
	next()
})

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})
//监听5000端口
app.listen(5000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

App.vue

<script>
import axios from 'axios'
export default {
  name: 'App',
  components: {
  },
  mounted() {
    //发送请求,注意,请求的端口是8080,而我们服务器监听的是5000端口
    axios.get('http://localhost:8080/students').then( response => {
        console.log(response.data)
    }).catch( error => {
        console.log(error.message)
    })
  }
}
</script>

1.3 执行node命令,打开服务监听

node serve1

1.4 启动vue项目

npm run serve

结果:

在这里插入图片描述

2. vue脚手架自带的跨域问题解决

关于跨域问题的具体说明和其他解决方案见:什么是跨域?跨域解决方法-CSDN博客

想通过vue脚手架自带的跨域解决,需要在 vue.config.js 中配置 devServer

2.1 基本配置

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
    devServer: {
        //配置serve1.js对应监听的端口
        proxy: 'http://localhost:5000'
    }
})

此时,需要重新运行vue项目

npm run serve

就能在控制台上看到请求的结果了,结果:
在这里插入图片描述
2.2 详细配置

详细配置可以精准控制自己本次请求需不需要代理转发

vue.config.js

//方式二:可以精准控制,看看自己本次请求需不需要代理
  devServer: {
    proxy: {
      //要代理需要加 api 前缀(http://localhost:XXX/api/xxxx),配合pathRewrite属性使用
      '/api': {	
        target: 'http://localhost:5000',
        pathRewrite: {'^/api':''}, //匹配端口号后面以/api开头的信息,将其变为空
        changeOrigin: true, //控制请求头中的host,服务器收到的是改变后的host信息
      }
    }
  }

App.vue

<script>
import axios from 'axios'
export default {
  name: 'App',
  components: {
  },
  mounted() {
    //发送请求,注意,请求的端口是8080,而我们服务器监听的是5000端口
    //注意,请求的url是 http://localhost:8080/api/students
    //配合vue.config.js中配置的pathReWrite可以将/api去掉
    //如果我们加了/api就是需要代理转发,没加则不需要
    axios.get('http://localhost:8080/api/students').then( response => {
        console.log(response.data)
    }).catch( error => {
        console.log(error.message)
    })
  }
}
</script>

结果:
在这里插入图片描述

举报

相关推荐

0 条评论