blocked by CORS policy: No 'Access-Control-Allow-Origin'跨域问题

这个问题折磨我一下午,google其他人的办法 也不灵 特此求助:
后端go 端口8000, 前端react 端口3000

报错信息:
Access to XMLHttpRequest at 'http://localhost:8000/api/v1/articles' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

router.go:

package routers

import (
	"gin-blog/cors"
	"gin-blog/pkg/setting"
	"gin-blog/routers/api"
	v1 "gin-blog/routers/api/v1"

	"github.com/gin-gonic/gin"
)

func InitRouter() *gin.Engine {
	r := gin.New()

	// 使用跨域中间件
	r.Use(cors.Cors())

	r.Use(gin.Logger())

	r.Use(gin.Recovery())

	gin.SetMode(setting.RunMode)

	r.GET("/auth", api.GetAuth)

cors.go:

package cors

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "false")
			c.Set("content-type", "application/json")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

前端app.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import axios from 'axios';

export default class app extends Component {
  constructor() {
      super()
      this.state = {
          getDataFromBase: ''
      }
  }
  componentDidMount() {
      alert(1234);

      axios({
          method:'get',
          url:'/api/v1/articles',
      }).then(function(res){
          console.log(res.data);
      }).catch(function(error){
          console.log(error);
      });

  }
  render() {
      return (
        <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo"  data-tomark-pass />
          <p>
            Edit <code>src/App.js</code> and save to reload134.
          </p>
  
          <p>
              <span>{this.state.getDataFromBase}</span>
          </p>

        </header>
      </div>
      )
  }
}

共 1 个回复


sinow

解决了 解决办法:

package.json里加
"proxy": "http://localhost:8000"

貌似不加:8000也可以

# 0