标签: axios

如何使用axios/AJAX与redux-thunk

我在我的行动中使用axios.我需要知道这是否是正确的做法.

actions/index.js ==>

import axios from 'axios';
import types from './actionTypes'
const APY_KEY = '2925805fa0bcb3f3df21bb0451f0358f';
const API_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${APY_KEY}`;

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  let promise = axios.get(url);

  return {
    type: types.FETCH_WEATHER,
    payload: promise
  };
}
Run Code Online (Sandbox Code Playgroud)

reducer_weather.js ==>

import actionTypes from '../actions/actionTypes'
export default function ReducerWeather (state = null, action = null) {
  console.log('ReducerWeather ', action, new Date(Date.now()));

  switch (action.type) {
    case actionTypes.FETCH_WEATHER:
          return action.payload;
  }

  return state;
}
Run Code Online (Sandbox Code Playgroud)

然后将它们组合在rootReducer.js ==>中

import { combineReducers …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs redux redux-thunk axios

20
推荐指数
1
解决办法
3万
查看次数

Chrome扩展程序中使用axios和webpack时出现TypeError:adapter is not a function错误

我正在构建一个 chrome 扩展,当从内容脚本收到某些消息时,该扩展需要进行 API 调用。我在发出 HTTP 请求时遇到困难,我相信我的 webpack 配置是罪魁祸首。

我尝试过使用node-fetchand axios,但都不适合我。

我的 webpack.common.js 文件如下所示:


const path = require("path");

module.exports = {
  target: "node",
  entry: {
    popup: path.join(__dirname, "src/popup/index.tsx"),
    background: path.join(__dirname, "src/background.ts"),
    contentScript: path.join(__dirname, "src/contentScript.ts"),
  },
  output: {
    path: path.join(__dirname, "dist"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /\.tsx?$/,
        use: "ts-loader",
      },
      {
        exclude: /node_modules/,
        test: /\.scss$/,
        use: [
          {
            loader: "style-loader", // Creates style nodes from JS strings
          },
          {
            loader: "css-loader", // …
Run Code Online (Sandbox Code Playgroud)

javascript google-chrome-extension typescript webpack axios

20
推荐指数
2
解决办法
2万
查看次数

在 npm run build 期间找不到名称“AbortSignal”

node_modules/axios/index.d.ts:93:12 - error TS2304: Cannot find name 'AbortSignal'.

93   signal?: AbortSignal;
              ~~~~~~~~~~~


Found 1 error.
Run Code Online (Sandbox Code Playgroud)

当尝试npm run build节点打字稿项目的命令时,我收到上述错误,与 axio 包相关。在使用 axio 之前, npm run build 工作正常。

build npm typescript axios

20
推荐指数
2
解决办法
1万
查看次数

无法加载响应数据:未找到具有给定标识符的资源的数据

我正在 React 中制作注册表单并尝试使用 axios API 发送请求。我在代码中没有收到任何错误,但是当我单击注册按钮,然后转到控制台,然后转到网络时,我发现它无法加载响应数据。

我收到的错误是:

无法加载响应数据:未找到具有给定标识符的资源的数据

export class Register extends React.Component {

    handleSubmit = e => {
        e.preventDefault();
        const data = {
            first_name: this.firstName,
            last_name: this.lastName,
            email: this.email,
            password: this.password,
            password_confirm: this.confirmPassword
        };

        axios.post('http://localhost:8000/Register', data).then(
            res => {
                console.log(res)
            }
        ).catch(
            err => {
                console.log(err);
            }
        )
    };

    render() {
        return (
            <form onSubmit={this.handleSubmit} >
                <h3>Sign Up</h3>

                <div className="form-group">
                    <label> First Name</label>
                    <input type="text" className="form-control" placeholder="First Name"
                        onChange={e => this.firstName = e.target.value} />
                </div>

                <div className="form-group">
                    <label> Last …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs axios

20
推荐指数
1
解决办法
4万
查看次数

不变:方法期望有 requestAsyncStorage,但没有可用的

我正在尝试使用 prisma 客户端从 mongodb atlas 检索用户的数据,我编写此代码用于获取数据,它显示错误,这里 prisma 客户端代码写入作为 prisma 导入的 prismadb 文件中

import { NextApiRequest, NextApiResponse } from "next";
import prisma from "./prismadb";
import { getServerSession } from "next-auth";

const serverAuth = async (req: NextApiRequest, res: NextApiResponse) => {
    try {
        const session = await getServerSession(req);

        if (!session?.user?.email) {
            throw new Error('Not signed in');
        }

        const currentUser = await prisma.user.findUnique({
            where: {
                email: session.user.email,
            }
        });

        if (!currentUser) {
            throw new Error('Not signed in');
        }

        return { currentUser };
    } …
Run Code Online (Sandbox Code Playgroud)

axios next.js next-auth

20
推荐指数
2
解决办法
3万
查看次数

从React(Isomorphic应用程序)进行API调用时出现"Access-Control-Allow-Origin"问题

我使用React和Express遇到了同构JavaScript应用程序的问题.

我正在尝试使用axios.get在我的组件安装时发出HTTP请求

componentDidMount() {
  const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
  axios.get(url).then( res => {
    //use res to update current state
  })
}
Run Code Online (Sandbox Code Playgroud)

我从API获得状态200 res,但我没有得到任何响应数据并在我的控制台中收到错误

XMLHttpRequest cannot load http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)

但是,如果我在server.js中发出请求

const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders';
axios.get(url).then(res => {
    //console.log(res);
});
Run Code Online (Sandbox Code Playgroud)

它工作正常,我在服务器启动时获得响应数据.这是实际API的问题还是我做错了什么?如果这是一个CORS问题,我猜测server.js中的请求也不起作用?谢谢!

javascript node.js reactjs isomorphic-javascript axios

19
推荐指数
6
解决办法
6万
查看次数

Vue js 2&Axios Post Request - Form

我正在尝试使用axios发布我的表单,但我无法使用expressjs将数据提供给我的后端

这就是我在做的事情:

<template>
 <form class="" method="post" @submit.prevent="postNow">
 <input type="text" name="" value="" v-model="name">
 <button type="submit" name="button">Submit</button>
 </form>
</template>

export default {
  name: 'formPost',
  data() {
    return {
      name: '',
      show: false,
    };
  },
  methods: {
   postNow() {
  axios.post('http://localhost:3030/api/new/post', {
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    body: this.name,
   });
  },
  components: {
    Headers,
    Footers,
  },
};
Run Code Online (Sandbox Code Playgroud)

后端文件:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/new/post', (req, res) => {
  res.json(console.log("this is working" + ' ' + req.body.name));
});
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

this is working undefined
Run Code Online (Sandbox Code Playgroud)

javascript node.js express vue.js axios

19
推荐指数
1
解决办法
4万
查看次数

使用React,Redux和Axios处理异步请求?

我是React JS和Redux的新手,而且它太过于无法胜任.我正在尝试使用Axios发出POST请求,但我无法做到.可能是我在容器文件中遗漏了一些东西.下面是代码.检查plnkr

更新: 提交后我收到@@ redux-form/SET_SUBMIT_SUCCEEDED消息.但是当我在网络选项卡中检查时,我看不到对API的调用.而且当我安慰提交的值时,我只看到名称和全名值.它不包含徽标和细节.我错过了什么?

组件文件

   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { Field,reduxForm } from 'redux-form'
   import {   Columns,Column, TextArea, Label,Button  } from 'bloomer'
   import FormField from 'FormField'

   const validate = (values) => {
     const errors = {}
    const requiredFields = 
      ['organizationName','organizationFullName','organizationDetails']

    requiredFields.forEach((field) => {
     if (!values[field]) {
     errors[field] = 'This field can\'t be empty!'
    }
  })
     return errors
}

  const formConfig = {
   validate,
   form: 'createOrganization',
   enableReinitialize: true
   }

  export class …
Run Code Online (Sandbox Code Playgroud)

reactjs redux redux-form axios

19
推荐指数
1
解决办法
7275
查看次数

Nestjs 使用 axios

这个简单的演示有一个错误 https://docs.nestjs.com/techniques/http-module

import { Get, Controller, HttpService } from '@nestjs/common';
import { AxiosResponse } from 'axios'
import { Observable } from 'rxjs'
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
  root(): Observable<AxiosResponse<any>>  {
    return this.http.get('https://api.github.com/users/januwA');
  }
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

[Nest] 7356   - 2018-10-18 00:08:59   [ExceptionsHandler] Converting circular structure to JSON +9852ms
TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
Run Code Online (Sandbox Code Playgroud)
nest i
common version : 5.1.0
core version   : 5.1.0
Run Code Online (Sandbox Code Playgroud)

javascript node.js axios nestjs

19
推荐指数
1
解决办法
2万
查看次数

如何正确设置带有 React Context 的 Axios 拦截器?

由于我想使用 React Context 设置 Axios 拦截器,因此似乎可行的唯一解决方案是创建一个拦截器组件,以便使用 useContext 挂钩来访问 Context 状态和分派。

问题是,这会创建一个闭包,并在调用拦截器时将旧数据返回给拦截器。

我正在使用 React/Node 使用 JWT 身份验证,并且我正在使用 Context API 存储访问令牌。

这就是我的拦截器组件现在的样子:

import React, { useEffect, useContext } from 'react';
import { Context } from '../../components/Store/Store';
import { useHistory } from 'react-router-dom';
import axios from 'axios';

const ax = axios.create();

const Interceptor = ({ children }) => {
  const [store, dispatch] = useContext(Context);

  const history = useHistory();

  const getRefreshToken = async () => {
    try {
      if (!store.user.token) {
        dispatch({
            type: 'setMain', …
Run Code Online (Sandbox Code Playgroud)

javascript jwt reactjs axios jwt-auth

19
推荐指数
1
解决办法
5225
查看次数