javascript nodejs - AxiosError:请求失败,状态代码为500

dxxyhpgq  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(122)

我试图转换下面的代码是使用请求模块axios模块发送POST请求。

请求模块编码:

const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";

var options = {
    'method': 'POST',
    'url': url,
    'headers': {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Accept': 'application/json'
    },
    formData: {
    'image': {
            'value': imageFile,
            'options': {
            'filename': imgName,
            'contentType': null
            }
        }
    }
};

request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log("SUCCESS");
});

字符串
上面的代码工作正常,图像通过请求模块成功发布。但是当我将其转换为axios时,我得到了一个500错误。(AxiosError:Request failed with status code 500

axios模块代码:

const FormData = require('form-data')

const imageFile = fs.createReadStream('image.jpeg');
const imgName = "image" + ".jpeg";

const bodyFormData = new FormData();
bodyFormData.append("image['value']", imageFile);
bodyFormData.append("image['options']['filename']", imgName)
// bodyFormData.append("image['options']['contentType']", null)
console.log(bodyFormData)

const formHeaders = bodyFormData.getHeaders();

axios.post(url, bodyFormData, {
    headers: { 
    ...formHeaders, 
    'Cache-Control': 'no-cache',
    'Accept': 'application/json',
}
}).then(function (response) {
    console.log('SUCCESS');
}).catch(function (error) {
    throw new Error(error);
});


有人能发现我在这里做错了什么吗?
除了使用form-data之外,还有其他方法可以使用axios发布图像吗?

3df52oht

3df52oht1#

请参阅FormData#append()的文档。您可以提供额外的数据,如文件名作为第三个 * 选项 * 参数

const bodyFormData = new FormData();

// Pass filename as a string
bodyFormData.append("image", imageFile, imgName);

// or to specify more meta-data, pass an object
bodyFormData.append("image", imageFile, {
  filename: imgName,
  contentType: "image/jpeg",
});

axios.post(url, bodyFormData, {
  headers: {
    Accept: "application/json",
    "Cache-Control": "no-cache",
    ...bodyFormData.getHeaders(),
  },
});

字符串
在幕后,request()使用完全相同的form-data库执行非常类似的操作。

dkqlctbz

dkqlctbz2#

在laravel 10项目中,vue 3出现了同样的错误。

Error and how to fix it as follwed , 
*Error :-    POST http://127.0.0.1:8000/api/saveEmployee 500 (Internal Server Error)
dispatchXhrRequest @ xhr.js:258
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:146
httpMethod @ Axios.js:185
wrap @ bind.js:5
registerEmployee @ Employee.vue:84
eval @ Employee.vue:5
fn._withMods.fn._withMods @ runtime-dom.esm-bundler.js:1398
callWithErrorHandling @ runtime-core.esm-bundler.js:158
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166
invoker @ runtime-dom.esm-bundler.js:595
Employee.vue:90 **Error...AxiosError: Request failed with status code 500***

字符串
代码示例在这里,Employee.vue

<template>
  <div class="container">
    <div class="row">
      <div class="col-md-4">
        <form @submit.prevent="registerEmployee" novalidate>
          <fieldset>
            <legend>Employee Registration</legend>
            <div class="form-group">
              <label class="form-label mt-4">Calling Name</label>
              <input
                type="text"
                class="form-control"
                placeholder="Enter Calling Name"
                v-model="this.employee.callingname"
              />
            </div>
            <div class="form-group">
              <label class="form-label mt-4">NIC</label>
              <input
                type="text"
                class="form-control"
                placeholder="Enter NIC Here"
                v-model="this.employee.nic"
              />
            </div>
            <br />

            <button type="submit" class="btn btn-primary">Register</button>
            <button type="Update" class="btn btn-warning">Clear</button>
          </fieldset>
        </form>
      </div>

      <div class="col-md-1"></div>
      <div class="col-md-7">
        <table class="table table-hover">
          <tr class="table-success">
            <th scope="row">Index</th>
            <td>Calling Name</td>
            <td>NIC</td>
          </tr>

          <tr
            v-for="(employee, index) in employees"
            v-bind:key="employee.id"
            class="table-info"
          >
            <td>#{{ index + 1 }}</td>
            <td>{{ employee.callingname }}</td>
            <td>{{ employee.nic }}</td>

            <button class="btn btn-outline-success">Register</button>
            <button class="btn btn-outline-primary">View</button>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>
<script>

import axios from "axios";

export default {
  name: "Employee",
  data() {
    return {
      employees: [],
      employee: {},

      callingname: "",
      nic: "",
    };
  },
  methods: {
    async registerEmployee() {
      const fd = new FormData();

      fd.append("callingname", this.employee.callingname);
      fd.append("nic", this.employee.nic);

      console.log("callingname" + this.employee.callingname);
      console.log("nic" + this.employee.nic);

      await axios
        .post("http://127.0.0.1:8000/api/saveEmployee", fd)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log("Error..." + error);
        });
    },

    async loadEmployee() {
      const url = "http://127.0.0.1:8000/api/getallemployee";

      await axios
        .get(url)
        .then((responce) => {
          this.employees = responce.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },

  mounted() {
    this.loadEmployee();
    console.log("  Employee Mounted is working ");
  },
};
</script>
<style>
button {
  margin: 5px;
  float: right;
}
table {
  margin: 10px;
}
</style>

pageController.phpclass,<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employee;

class EmployeeController extends Controller
{
    
    public function insertEmployee(Request $req){

    try {
        $employees =  new Employee();
        $employees->callingname = $req.callingname;
        $employees->nic = $req.nic;
        $employees->save();

        return response()->json([
            'msg' => 'Successfully Added',
            'status' => 200
        ]);
    } catch (Exception $e) {
        // Log the error
        Log::error($e->getMessage());
        
        // Return an error response
        return response()->json([
            'error' => 'Internal Server Error',
            'status' => 500
        ], 500);
    }

 }

 

 public function getAllEmployee(){
     
     $employee = Employee::all();
     return response()->json($employee);
 }

}

API.phphere <?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GenderController;

use App\Http\Controllers\StudentController;
use App\Http\Controllers\EmployeeController;

// /*
// |--------------------------------------------------------------------------
// | API Routes
// |--------------------------------------------------------------------------
// |
// | Here is where you can register API routes for your application. These
// | routes are loaded by the RouteServiceProvider and all of them will
// | be assigned to the "api" middleware group. Make something great!
// |
// */

// Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
//     return $request->user();
// });

Route::get('contactsapi', 
[App\Http\Controllers\ContactController::class,'contactsMethod']);

Route::post('savecontactsapi', 
[App\Http\Controllers\ContactController::class,'saveContactsMethod']);

Route::delete('deletecontactsapi/{id}', 
[App\Http\Controllers\ContactController::class,'deleteContactsMethod']);

Route::post('updatecontactsapi/{id}', 
[App\Http\Controllers\ContactController::class,'updateContactsMethod']);

Route::get('getcontactsapi/{id}', 
[App\Http\Controllers\ContactController::class,'getContact']); 

Route::get('getcontactsbyname/{name}', 
[App\Http\Controllers\ContactController::class,'getContactByName']);

Route::get('getcontactsbyemail/{email}', 
[App\Http\Controllers\ContactController::class,'getContactByEmail']); 

Route::get('getcontactsbycontactno/{contactno}', 
[App\Http\Controllers\ContactController::class,'getContactByContactNo']); 

Route::get('/genders', [GenderController::class, 'gendersMethod']);

Route::get('getgenderapi/{id}', 
[App\Http\Controllers\GenderController::class,'getGender']); 

Route::get('getallstudents',[StudentController::class,'getAllStudents']);
Route::post('savestu', 
[App\Http\Controllers\StudentController::class,'insertStu']);

Route::get('getallemployee',[EmployeeController::class,'getAllEmployee']);

Route::post('saveEmployee', 
[App\Http\Controllers\EmployeeController::class,'insertEmployee']);


上面的egsamples产生了相同的错误,问题的根源是语法错误。我们可以像下面这样修复它,

$employees->callingname = $req -> callingname;
$employees->nic = $req -> nic;

  • 我们希望使用正确的语法来解决上述问题使用-> insted of .(点)*

相关问题