前端
1.下载axios,在命令行下载
npm install axios --save
2.配置vue.config.js
const path = require('path');
module.exports = {
configureWebpack: {
resolve: {
alias: {
'pdfjs-dist': path.join(__dirname, 'node_modules/pdfjs-dist')
}
}
},
devServer: {
port: 5173, // 设置本地默认端口
proxy: {
'/api': { // 设置代理,拦截以 '/api' 开头的请求
target: 'http://localhost:8080', // 代理的目标地址
changeOrigin: true, // 允许跨域
pathRewrite: {
'^/api': '' // 移除请求路径中的 '/api' 前缀
}
}
}
},
chainWebpack: config => {
config.module
.rule('pdf')
.test(/\.worker\.js$/)
.use('worker-loader')
.loader('worker-loader')
.options({
filename: 'pdf.worker.[hash].js'
})
.end();
config.module
.rule('images')
.test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
.use('url-loader')
.loader('url-loader')
.options({
limit: 10000, // 小于 10kb 的图片将转为 base64 编码
name: 'img/[name].[hash:7].[ext]', // 输出到 dist/img/ 目录下
// 其他选项...
});
},
// ... 其他配置 ...
};
3.配置vite.config.js
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'http://localhost:8080/', // 你的后端服务地址
changeOrigin: true, // 如果你的API请求需要跨域
pathRewrite: { //路径重写
'^/api': '' //选择忽略拦截器里面的内容
}
}
},
hmr: {
overlay: false
}
}
})
4.前端页面向后端发起请求
例如在CreatPPT.vue页面里面实现如下操作
sendData() {
const message = this.searchInput;
axios.post('http://localhost:8080/create/async', message, {
headers: {
'Content-Type': 'text/plain'
}
})
.then(response => {
console.log('Data sent successfully', response.data);
this.$router.push({
path: '/outline',
query: { outline: response.data }
});
})
.catch(error => {
console.error('Error sending data:', error);
});
}
},
};
后端:
一个找了两个小时的错误!!!
注意端口号要和前端保持一致且不能重复
package com.example.ppt_project_backend.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author
* @description 跨域配置
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
}