在使用代理的情况下,后端不需要再设置跨域。代理的作用是将前端的请求转发到后端,并在转发过程中自动处理跨域问题。因此,只需要在前端的配置中设置代理即可实现跨域。

具体来说,可以在 'vue.config.js' 文件中配置代理:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

上述代码中,我们将以 '/api' 开头的请求转发到 'http://localhost:5000',同时启用了 'changeOrigin' 选项和 'pathRewrite' 选项。'changeOrigin' 选项表示是否改变请求头中的 Origin 字段,'pathRewrite' 选项用于重写请求路径。

在后端的代码中,不需要做任何跨域设置,直接处理请求即可。例如:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        // 处理请求
    }
}

通过代理,前端和后端的跨域问题得到了完美解决。

Vue3 前端代理配置,如何解决 Net6 WebAPI 跨域问题

原文地址: https://www.cveoy.top/t/topic/lAVS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录