标签: axios

$request->ajax() 在 ajax 调用中返回 false

我想提出一个Ajax请求有axios一个laravel controller,我想用一个middleware检查,如果request与制作ajax,但问题是,当我做出ajax request,middleware罚球false始终。

我这样打电话

axios.post('/api/contact/send', {
    ...
    data : data
}).then((response) => {
    Do somethings
}).catch(err => {
    Do somethings
})
Run Code Online (Sandbox Code Playgroud)

我的 api 路由

Route::namespace('Home')->middleware('IsAjaxRequest')->domain(env('HOST'))->group(function(){
    ....
    Route::post('contact/send','ContactController@postContact');
});
Run Code Online (Sandbox Code Playgroud)

IsAjaxRequest中间件

if(!$request->ajax()) {
    abort(403, 'Unauthorized action.');
}
return $next($request);
Run Code Online (Sandbox Code Playgroud)

和控制器

<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Events\Home\ContactMail;
use App\Http\Controllers\Controller;

use App\Http\Requests\ContactRequest;
class ContactController extends Controller
{
    //
    public function postContact(ContactRequest $request)
    {

        $data  = …
Run Code Online (Sandbox Code Playgroud)

javascript ajax middleware laravel axios

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

来自 vue 组件的 laravel 表单请求的 422 响应中没有错误消息

我正在尝试使用 axios 提交表单请求,对其进行验证,如果验证失败则返回错误。问题是,当我提交表单时,没有返回错误消息让我在客户端显示。这是HTTP 请求和 vue 组件

         <div class="card">
            <div class="card-header">
                    <h4>Information</h4>
            </div>

        <div class="card-body">
            <p v-if='!isEditMode'><strong>Name:</strong> {{businessData.name}}</p> 
            <div class="form-group" v-if='isEditMode'>
                <strong><label for="business-name">Name</label></strong> 
                <input class="form-control" name="business-name"  v-model='businessData.name'>
            </div>
            <p v-if='!isEditMode'><strong>Description:</strong> {{businessData.description}}</p> 
            <div class="form-group" v-if='isEditMode'>
                <strong><label for="business-description">Description</label></strong> 
                <textarea class="form-control normal" name="business-description" 
                    placeholder="Enter your services, what you sell, and why your business is awesome" 
                    v-model='businessData.description'></textarea>
            </div>
        </div>

    </div>

    <div class="card">
        <h4 class="card-header">Address Information</h4>
        <div class="card-body">

            <p v-if="!isEditMode"><strong>Street Address: </strong> {{businessData.street}}</p>
            <div class="form-group" v-if='isEditMode'>
                <strong><label for="business-street">Street Address: </label></strong> 
                <input type="text" class="form-control" name="business-street" …
Run Code Online (Sandbox Code Playgroud)

laravel axios vuejs2

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

用axios发送后表单数据为空

我送一个FormDataVueJS应用程序中使用Axios。问题是当我输出FormData它时它是空的。我之前在发送文件时使用过相同的方法(我现在不发送文件),然后FormData显示我附加到它的正确数据。我附加的数据是字符串类型。

客户端

onUpload(): void {
      const fd = new FormData();
      fd.append("id", this.chosenRoute.id);
      fd.append("name", this.routeName);
      fd.append("description", this.routeDescription);
      fd.append("activity", this.activity);
      fd.append("preamble", this.preamble);
      axios.post('http://localhost:8080/editRoute', fd, {
      onUploadProgress: uploadEvent => {
        console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
      }
    }).then(
      res => {
      console.log(res);
    });
  }
Run Code Online (Sandbox Code Playgroud)

服务器端

app.post('/editRoute', function(req,res){
    console.log(req.body);
    const routeId = req.body.id;
    console.log(routeId);
    Route.findById(routeId, (err, route) => {
        res.set("Access-Control-Allow-Origin", "*");
        route.update(req.body);
    });
});
Run Code Online (Sandbox Code Playgroud)

multipartform-data node.js express vue.js axios

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

Axios 在控制台上打印值但返回未定义

一段时间以来,我遇到了一个相当大的问题,并且让我很紧张,这没有意义。我在我的 React 前端使用了 axios,它在将 get 值分配给状态时效果很好。但是当在普通的 javascript 代码中使用它时,我似乎有以下问题:我可以在控制台中打印对象的值,但它只会返回 undefined .. 这是我的代码:

login = () => {
        let data;
        axios.get('https://myaddress/authenticate')
            .then(response => {
                data = response;
                console.log('data here', data);
            })
            .catch(error => {
                console.error('auth.error', error);
            });
        console.log('eee', data);
        return data;
    };
Run Code Online (Sandbox Code Playgroud)

这里我们严格地谈论 axios。

javascript axios

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

finally() 在 Vuejs 另一个应用程序中不起作用

最近我做了这个教程。

在这个应用程序中,我可以成功运行 vuejs 应用程序和axios.then.catch.finallythis.form.then.catch.finally.

但是我在我最近升级到 Laravel 5.7 的旧项目中添加了 npm。在我的应用程序中,我无法添加finally功能。如果我这样做,它说:

未捕获的类型错误:axios.post(...).then(...).catch(...).finally 不是函数

我的 app.js:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

// require('./bootstrap');
import Vue from 'vue'
window.Vue = Vue
window.axios = require('axios');
import { Form, HasError, AlertError } from 'vform'
window.Form = …
Run Code Online (Sandbox Code Playgroud)

vue.js laravel-5 axios

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

Laravel, Vue.js | 通过 axios 请求下载空白 pdf

我一直在尝试通过 axios 从我的 Laravel 应用程序下载 PDF,但下载的文件是一个空的 pdf。

我正在使用 DomPdf 创建 pdf 并使用 download.js 下载它,下面是我的代码。

注意:如果我尝试在没有 ajax 请求的情况下下载它,它工作得很好。

拉拉维尔,

return PDF::loadView('print', compact('bill'))->download($bill->number.'.pdf'); Javascript

``axios.get(`/bills/${id}/print` {
responseType: 'blob',Accept: 'application/pdf'
})
.then(response => {
  const download = require('@/download');
  // @ is just an alias for my root js directory.
  download(response.data, `file.pdf`, 'application/pdf');
});``
Run Code Online (Sandbox Code Playgroud)

javascript dompdf laravel vue.js axios

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

使用 Vue 处理来自 Express API 的错误

我在访问以 400 错误返回的 JSON 对象时遇到了一些困难。

我的 Vue 应用程序的响应只是错误 400,没有 JSON 数据。

Error: Request failed with status code 400
    at createError (createError.js?16d0:16)
    at settle (settle.js?db52:18)
    at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)
Run Code Online (Sandbox Code Playgroud)

使用 Postman 的响应返回错误代码和消息。

如何在我的 Vue 应用程序中访问 JSON 响应?

{
    "error": "Email already exists!"
}
Run Code Online (Sandbox Code Playgroud)

快速API代码:

res.status(400).json({ error: 'Email already exists!' });

我的Vue代码:

handleSubmit () {
  this.$http.post('http://localhost:3000/users/create', this.user)
      .then(response => {
          const status = JSON.parse(response.status)
          if (status === 200) router.push('/users')
      })
      // why doesn't the json response show
      .catch(err => {
          console.log(err)
      })
}
Run Code Online (Sandbox Code Playgroud)

json node.js express vue.js axios

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

在 Axios、Nodejs 中发布带有文件的多部分表单

const form_data = new FormData();
form_data.append("File", fs.createReadStream(pathToFile));
form_data.append('Login', alias.toUpperCase());

const request_config = {
    headers: {
        "Authorization": "Basic 123",
        "Content-Type": 'multipart/form-data'
    },
    data: form_data
};

await axios.post(url, params, request_config).then(response => {
Run Code Online (Sandbox Code Playgroud)

发布到我无法调试的端点。答案是 500。

这是错误:

在此处输入图片说明

这是正确的方法吗?

我能以某种方式确切地看到 Axios 发送的内容吗?

这是我从 API 的作者那里收到的邮递员请求。这通过:

POST /api/upload HTTP/1.1

Host: api.test.contoso.se

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

Authorization: Basic 123

User-Agent: PostmanRuntime/7.13.0

Accept: */*

Cache-Control: no-cache

Postman-Token: 089af753-fa12-46c4-326f-dfc39c36faab,c5977145-ece3-4b53-93ff-057788eb0dcf

Host: api.test.contoso.se

accept-encoding: gzip, deflate

content-length: 18354

Connection: keep-alive

cache-control: no-cache

Content-Disposition: form-data; name="Lang"

SV
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Content-Disposition: form-data; name="File"; filename="/C:/Users/file.docx


------WebKitFormBoundary7MA4YWxkTrZu0gW-- …
Run Code Online (Sandbox Code Playgroud)

http node.js axios

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

axios + 查询字符串

我想知道如何使用查询字符串 npm 包来简化我的 axios 调用。我使用的包是:https : //www.npmjs.com/package/query-string

一个例子:

import qs from 'query-string';
import axios from 'axios';

axios.get(`http://localhost:3000/api/products${qs.parse({ offset: 0, limit: 12 })}`);
Run Code Online (Sandbox Code Playgroud)

不知道为什么,但这不能按预期工作。

javascript query-string axios

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

无法访问功能内的道具

我想在使用 axios 获取数据后访问 props 中的函数,但出现错误:

期望赋值或函数调用,却看到了一个表达式 no-unused-expressions

我可以在 jsx 中访问相同的函数,但是当我尝试从函数 / axios 调用它时它不起作用。这是我的代码:

function LoginModal(props) {


let emailInput = React.createRef();
let passwordInput = React.createRef();



const getToken = (props) => {
    axios.post('http://localhost:8000/api/token/', {
        username: emailInput.current.value,
        password: passwordInput.current.value
      })
      .then(function (response) {
        props.closeModalHandler();
      })

}

return (
    <div className={styles.Background} onClick={props.closeModalHandler}>
    <div className={styles.ModalContainer}>
        <h2>Log in.</h2>
        <div className={styles.InputContainer}>
            <input type="text" className={styles.Input} ref={emailInput} />
            <label htmlFor="" className={styles.ActiveLabel}>Email</label>
        </div>
        <div className={styles.InputContainer}>
            <input type="password" className={styles.Input} ref={passwordInput}/>
            <label htmlFor="" className={styles.ActiveLabel}>Password</label>
        </div>
        <button className={styles.LoginButton}
                onClick={getToken}>Log me in</button>
        <p>Forgot password? …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs axios

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