标签: axios

Reactjs通过axios POST请求

您好,我正在尝试通过 axios 进行 ReactJS POST 请求,但出现错误,我浏览了所有文档,但错误尚未解决。

这是我的错误:

未捕获(承诺中)错误:请求失败,状态代码为 400 at createError (eval at (bundle.js:4621), :15:15) at Settle (eval at (bundle.js:4615), :18:12) at XMLHttpRequest.handleLoad(在(bundle.js:4609),:77:7处评估)

这是我的 Reactjs 代码:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}


handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: …
Run Code Online (Sandbox Code Playgroud)

javascript java reactjs axios

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

当所有嵌套的 Axios 调用完成时 ReactJS setState

我在通过 forEach 循环内的嵌套 axios 调用更新状态时遇到问题:

constructor(props) {
    super(props);
    this.state = {
      isLoaded: false,
      items: []
    };
    //Binding fetch function to component's this
    this.fetchFiles = this.fetchFiles.bind(this);
  }

  componentDidMount() {
    this.fetchFiles();
  }

  fetchFiles() {
    axios.get('/list')
    .then((response) => {
      var items = response.data.entries;
      items.forEach((item, index) => {
        axios.get('/download'+ item.path_lower)
        .then((response) => {
          item.link = response.data;
        })
        .catch(error => {
          console.log(error);
        })
      });
      this.setState(prevState => ({
        isLoaded: true,
        items: items
      }));
      console.log(this.state.items);
    })
    .catch((error) => {
      console.log(error);
    })
  }
Run Code Online (Sandbox Code Playgroud)

这个想法是使用 Dropbox 的 API (JavaScript …

asynchronous async-await reactjs es6-promise axios

0
推荐指数
1
解决办法
1950
查看次数

如何防止最终用户看到通过浏览器控制台进行的网络调用

我需要在所有 ajax 调用中发送一个特定的标头参数,这是一个非常机密的信息。我不希望最终用户看到在任何浏览器的网络选项卡中发出的任何请求。有什么办法可以预防吗?或者是否可以直接从节点服务器进行ajax调用而不通过浏览器?

javascript browser ajax node.js axios

0
推荐指数
1
解决办法
5117
查看次数

使用 forEach 和 axios 进行异步/等待

我遇到了一个问题,需要你的帮助。我需要在名为 rudder 的软件中使用自动注册服务器的 API。为了达到我的目标,我必须使用 2 个 http 请求:

  1. (GET) 获取所有处于挂起状态的服务器
  2. (POST)注册我的服务器

我的第一个请求得到了完美处理,但我不知道如何实现第二个请求。

这是我的代码(/src/controllers/registration.js):

async function index(req, res) {
  // Check parameter
  if (!req.body.hostname) {
    return res.status(422).json({ result: 'error', message: 'Missing hostname parameter' });
  }

  try {
    const pendingNodes = await axios.get(`${config.rudderURL}/rudder/api/latest/nodes/pending?include=minimal`, { headers });
    Object.keys(pendingNodes.data.data.nodes).forEach((key) => {
      // Search in all pending machine if our node is present
      const node = pendingNodes.data.data.nodes[key];
      if (req.body.hostname === node.hostname) {
        // Registration
        const response = async axios.get(`${config.rudderURL}/rudder/api/nodes/pending/${node.id}`, { headers });
        // console.log(response);
        return …
Run Code Online (Sandbox Code Playgroud)

javascript node.js async-await axios

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

Go Echo 未从 Vue 获取 POST 正文

我有 SignUp 函数并尝试获取 Vue 框架发送的请求正文,但它是空的。

type SignUpForm struct {
    Username string
    Email    string
    Password string
}

func SignUp(c echo.Context) error {
    form := SignUpForm{
        Username: c.FormValue("username"),
        Email:    c.FormValue("email"),
        Password: c.FormValue("password")}

    user := models.User{
        Username: form.Username,
        Email:    form.Email,
        Password: models.HashPassword(form.Password),
    }

    log.Printf("#####################")
    values, _ := c.FormParams()
    log.Printf("%v\n", values)
    log.Printf("%v", c.Response().Header())
    log.Printf("#####################")

    err := database.Connection().Create(&user).Error
    if err != nil {
        return c.JSON(http.StatusInternalServerError, err)
    } else {
        return generateJwtToken(c, user)
    }
}
Run Code Online (Sandbox Code Playgroud)

维埃

 sendForm: function() {
  var link = '/auth/sign_up'
  axios.post(link, { …
Run Code Online (Sandbox Code Playgroud)

javascript http go vue.js axios

0
推荐指数
1
解决办法
3460
查看次数

php cors 与 axios post 的问题

我有一个简单的 post 请求,使用 axios 到 php 脚本,它呈现一些 pdf 文件并应返回一个字符串。

现在我得到了这个错误:

Access to XMLHttpRequest at 'IP:7580/pdfgen/pdfGen.php' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
Run Code Online (Sandbox Code Playgroud)

我在我的 php 文件中设置了这个:

<?php
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');
Run Code Online (Sandbox Code Playgroud)

没有任何改变。也尝试过这个:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
Run Code Online (Sandbox Code Playgroud)

也没有变化。

我的 axios 调用如下所示:

axios.post("http://IP:7580/pdfgen/pdfGen.php", this.state)
        .then(response => {
            report = {...this.state.report};
            report.createdAt = reportCreatedAt;

            window.open(response.data);


            this.setState({report: report, pdf: response.data});
            console.log(response);
        })
Run Code Online (Sandbox Code Playgroud)

什么可以解决这个问题?

提前致谢

php cors axios

0
推荐指数
1
解决办法
4692
查看次数

无法使用 Axios 在 formData 内发送数组

我正在使用 vuejs 开发一个项目,并使用 Axios 处理我的 AJAX 请求,问题是我无法在 formData 内发送数组,我在开发人员面板的网络选项卡中看到我的请求上的 [object]。是否可以将主对象内的对象数组作为参数传递给 POST 请求,这种类型:在我的对象内,我有一个长度为 2 的数组,如下所示

\n\n
  (3) [{\xe2\x80\xa6}, {\xe2\x80\xa6}, {\xe2\x80\xa6}, __ob__: Observer]\n  0:\n  created_at: "2018-12-16 18:37:00"\n  id: 1\n  properties: Array(8)\n  0: {\xe2\x80\xa6}\n  1: {\xe2\x80\xa6}\n  2: {\xe2\x80\xa6}\n  3: {\xe2\x80\xa6}\n  4: {\xe2\x80\xa6}\n  5: {\xe2\x80\xa6}\n  6: {\xe2\x80\xa6}\n  7: {\xe2\x80\xa6}\n  title: "Building properties"\n  updated_at: "2018-12-16 18:37:00"\n __proto__: Object\n 1: {\xe2\x80\xa6}\n 2: {\xe2\x80\xa6}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试了 JSON.stringy 来处理数组和整个对象,但我得到 405 method not allowed。我也尝试添加配置。我看到一些解决方案作为 paramsSerializer 但无法理解我应该在哪里准确地编写它。

\n\n
   var data = {\n    user_id: this.user_info,\n    type_id: this.dorm_type,\n    city_id: this.city,\n    district_id: this.district,\n …
Run Code Online (Sandbox Code Playgroud)

javascript axios

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

当我使用 axios POST 时,Req.body 为空,但当我使用“request”时,它工作正常

一点背景知识 - 我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端口 3001 的所有请求 -

"proxy": "http://localhost:3001"
Run Code Online (Sandbox Code Playgroud)

现在,当我在 React 应用程序中使用 Axios 对 NodeJS 服务器上的“用户/身份验证”路由发出 POST 请求时,请求正文在 Node 服务器上被解析为空白

const request = {
            method: 'POST',
            url: `/users/authenticate`,
            headers: {
                'Content-Type': 'application/json'
            },
            body: {
                email: email,
                password: password
            }
        };
        console.log(request);
        axios(request).then((res) => {
            //handle success 
        });
        }).catch((err) => //handleError ))
Run Code Online (Sandbox Code Playgroud)

但不幸的是,NodeJS 应用程序崩溃了,因为它将 req.body 解析为空白。服务器端的相关代码 -

//in index.js file
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

app.use('/users', users);

//in users.js …
Run Code Online (Sandbox Code Playgroud)

javascript node.js express reactjs axios

0
推荐指数
1
解决办法
2304
查看次数

模拟 axios 时可以使用 URL 通配符吗?

我想知道是否可以使用通配符模拟某些 URL,例如所有以/auth. 我可以做类似的事情/auth*吗?

javascript axios axios-mock-adapter

0
推荐指数
1
解决办法
2920
查看次数

如果音频文件位于另一台服务器上,如何通过express.js 引导音频文件的流

我有一个处理程序express.js,它将文件的ID 作为输入。

我不知道如何通过 axios 等捕获该文件的流并将其传输到客户端部分 SPA。

感谢您的关注

router.get('/api/track/:id', async(req, res) => {
  // Create bot
  const telegram = new Telegram(token, { agent })
  const fileId = req.params.id

  let url
  try {
    // Getting filelink from telegram
    url = await telegram.getFileLink(fileId)
  } catch (error) {
    console.log('Error on getting link on file from telegram', error)
    return { message: 'Error on getting link on file from telegram', code: 4, error}
  }
  
  res.set('content-type', 'audio/mp3');
  res.set('accept-ranges', 'bytes');
  
  // And this is place i'm try download …
Run Code Online (Sandbox Code Playgroud)

node.js express telegram-bot axios

0
推荐指数
1
解决办法
2785
查看次数