axios 请求被阻止 | Reactjs

我试图使用我的reactjs代码中的端点axios,但请求被阻止,并且我在控制台中收到以下错误。

请建议如何克服这个问题

https://img1.sycdn.imooc.com/657ac3630001042612680153.jpg

下面是我的代码


import * as React from 'react';

import axios from "axios"

export default function App()

{

  return (

    <>

      <button onClick={fetchdata}>Click Me</button>

    </>

  )

}


function fetchdata()

{


  const axios = require('axios');

  

  // Make a request for a user with a given ID

  return axios.get('https://randomuser.me/api')

    .then(response => {

      // handle success

      console.log(response);

      return response;

    })

    .catch(error => {

      // handle error

      console.log(error);

  })

}


撒科打诨
浏览 115回答 2
2回答

波斯汪

您收到此错误的原因是因为https://randomuser.me期望使用 https 协议来自安全来源的请求,并且默认情况下 localhost 不会通过 https 运行。如果不满足这一点,您的浏览器将作为警告/错误返回。但是,如果您使用以下方法生成了 React 项目,create-react-app则可以在 package.json 中添加以下脚本:"proxy": "https://randomuser.me"

万千封印

工作正常,请检查这里Codesandbox:https://codesandbox.io/s/muddy-dust-yvotv?file=/src/ App.js有时出现此错误是因为您在浏览器中启动了 cors 的任何插件/扩展
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript