zl程序教程

您现在的位置是:首页 >  后端

当前栏目

axios 跨域问题_前端跨域产生的原因和解决方法

方法前端跨域 问题 解决 原因 产生 Axios
2023-06-13 09:13:39 时间

大家好,又见面了,我是你们的朋友全栈君。

首先,经典报错:No ‘Access-Control-Allow-Origin’

解决方法:

一、配置main.js

此处已经默认请求都添加/api为前缀

import Vue from 'vue'
import App from './App.vue'
import router from './router'

import axios from 'axios'
import 'font-awesome/css/font-awesome.min.css'

Vue.config.productionTip = false

axios.defaults.baseURL='/api/'
Vue.prototype.$axios = axios


new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

二、配置config.index.js

也就是在proxyTable中写上目标地址,主要是已经重写过/api了,之后的axios请求中都不需要再添加/api,也就是

pathRewrite: {

“^/api”:”

}

不需要写作下面这样, 会重复导致报错。

pathRewrite: {

“^/api”:“/api”

}

正确的index.js代码:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: { // 配置代理,下面是个例子
      '/api': {
        target: 'http://localhost:8880',
        changeOrigin: true,
        ws:true,
        pathRewrite: {
          "^/api":''
        }
      }
    },
 
    // host: 'localhost', // can be overwritten by process.env.HOST
    host: '0.0.0.0', // can be overwritten by process.env.HOST
    port: 3000, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false,  
    useEslint: true,
 
    showEslintErrorsInOverlay: false,
    devtool: 'cheap-module-eval-source-map',
    cacheBusting: true,
    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
   // assetsPublicPath: '/',
    assetsPublicPath: './', // 生产环境打包后静态文件路径修改为相对路径
    /**
     * Source Maps
     */

   // productionSourceMap: true,
    productionSourceMap: process.env.env_config !== 'prod', // 生产环境不需要sourceMap,测试阶段可为true
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    bundleAnalyzerReport: process.env.npm_config_report || true
  }
}

三、写请求:get请求为例

axios.get('/student',{//你想访问的资源
  params:{
    name:"邹xx"//因为后端使用findbyname函数
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(error){
  console.log(error);
});

四、顺手又写出404

404 Not Found 请求失败,请求所希望得到的资源未被在服务器上发现

没有这个路径,

@RestController

public class Studentcontroller {

    @Autowired
    StudentService studentService;

    @RequestMapping("/deletestudent")
    public void deletebyID(){
//        Optional<StudentEntity> byId = studentRepository.findById(13869L);
//        byId.orElse(null);
//        StudentEntity studentEntity = new StudentEntity();
//        studentEntity.setName("xxb");
//        studentRepository.save(studentEntity);
    }

    @GetMapping("/{name}")
    public StudentEntity findByName(@PathVariable("name") String name){
        return studentService.findByName(name);
    }

查看自己的路径,就是服务器端的问题

GetMapping 注解已经默认封装了@RequestMapping

使用postman测试

数据库中此人确实存在:

参数理解:

@GetMapping(value = "/service", params = "serviceName=CREATE_PROJECT")

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/194900.html原文链接:https://javaforall.cn