最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Axios is undefined in React, error: Uncaught TypeError: Cannot read property 'post' of undefined -

programmeradmin3浏览0评论

I have installed the axios package with: npm i axios. I import it in my redux action and Im trying to axios.post(), but the axios object is undefined. It posts successfully with .fetch() I'm using "axios": "^0.19.2" & "react": "^16.13.0".

import { axios } from "axios";

// Login User
export const login = () => dispatch => {
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: "[email protected]", password: "password" })
    };
    axios.post("/login", requestOptions)
      .then(response => response.json())
  };

I have installed the axios package with: npm i axios. I import it in my redux action and Im trying to axios.post(), but the axios object is undefined. It posts successfully with .fetch() I'm using "axios": "^0.19.2" & "react": "^16.13.0".

import { axios } from "axios";

// Login User
export const login = () => dispatch => {
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: "[email protected]", password: "password" })
    };
    axios.post("https://freunder.uber.space/login", requestOptions)
      .then(response => response.json())
  };

Browser error

Share Improve this question asked Mar 19, 2020 at 18:53 youhatchyouhatch 3412 gold badges4 silver badges10 bronze badges 2
  • Axios uses a default export, not a named export. Change it to import axios from "axios"; – Nicholas Tower Commented Mar 19, 2020 at 18:59
  • Change import { axios } from "axios"; to: import axios from "axios"; – Guilherme Toti Commented Mar 19, 2020 at 19:10
Add a ment  | 

2 Answers 2

Reset to default 14

Import axios as a default instead of a named export like so:

// This
import axios from 'axios';

// Instead of this
import { axios } from "axios";

I tried you code, its returning 401 error and i am not facing the error you posted . You can see the response as well

The response :

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论