403 在 LocalHost 上被禁止?

问题描述 投票:0回答:1

我在端口 3001 托管一个 React localhost,并尝试从 localhost5000 获取。然而,我不断遇到 403 Forbidden 错误,即使它是在我自己的计算机上。我完全不知道如何解决这个问题。我尝试通过将本地主机放入 Edge 来检查本地主机,但仍然收到 403 Forbidden 错误。我知道 pytrends 有效,因为我在没有 FastAPI 的情况下尝试它并且可以从中获取数据。

  const [inputText, setInputText] = useState('');
  const [score, setScore] = useState(null);
  const [last5Entries, setLast5Entries] = useState();

  const calculateScore = async () => {
    try {
      const response = await axios.post("http://localhost:5000/pytrends", { 'text': inputText });
      console.log(response);
      const interest = response.data.interest; //TO BE IMPLEMENTED (get score somehow)
      const score = response.score;
      setScore(score);
    }
    catch (error) {
      console.error('Error calculating niche score:', error);
    }
  }

  return (
    #some html 
  );
};

export default App;
@app.post("/pytrends")
async def trend_data(request: Request):
    pytrends = TrendReq(hl='en-US', tz=360)
    # Get user input as a list
    kw_list = request.json()['text']#gets JSON and extracts the input keyword

    pytrends.build_payload(kw_list, cat=0, timeframe='today 12-m', geo='', gprop='')  # Builds payload for keyword and interest over the last 12 months
    data = pytrends.interest_over_time()  # Returns pandas.DataFrame

    # Calculate the niche score by summing the 'score' column
    niche_score = data[kw_list[0]].sum()

    # Create a dictionary with the interest and score
    data_dict = {"interest": kw_list[0], "score": niche_score}

    # Add the current row to the DataFrame
    global df
    df = pd.concat([df, pd.DataFrame([data_dict])], ignore_index=True)

    return {"score": niche_score}```


python reactjs fastapi
1个回答
0
投票

这可能是 CORS 问题:默认情况下,您的 FastAPI 应用程序会告诉您的浏览器不要接受来自

localhost:3000
的请求。

您可以通过添加来解决此问题:

from fastapi.middleware.cors import CORSMiddleware

origins = [
    "http://localhost:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

(参考自https://fastapi.tiangolo.com/tutorial/cors/

© www.soinside.com 2019 - 2024. All rights reserved.