最后一个Web项目,采用前后端分离。
前端:Vue 3.0 + vite+element plus
后端:PHP
运行时前端和后端是两个程序,前端需要时才向后端请求数据。由于是两个程序,这就会出现跨域问题。
比如前端某个地方需要请求的接口如下所示,这时就会报错。
- axios.post('http://localhost/cesiumphp/index.php?action=add', jsonObject)
- .then((response) => {
- console.log(response);
- })
- .catch((error) => {
- console.error(error);
- });
-
- console.log(jsonString);
- }
- }
解决办法:
1.将http://localhost:80(注端口为80时可以省略)替换为api
- axios.post('api/cesiumphp/index.php?action=add', jsonObject)
- .then((response) => {
- console.log(response);
- })
- .catch((error) => {
- console.error(error);
- });
-
- console.log(jsonString);
- }
- }
2.在vite.config.ts中增加代理配置,将http://localhost:80
- import { defineConfig } from 'vite'
- import vue from '@vitejs/plugin-vue'
-
- // https://vitejs.dev/config/
- export default defineConfig({
- plugins: [vue()],
- server: {
- proxy: {
- '/api': {
- target: 'http://localhost:80',
- changeOrigin: true,
- rewrite: path => path.replace(/^\/api/, '')
- }
- }
- }
- })
-
现在不报错了。