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

问题描述 投票:0回答:2

我正在尝试将以下使用请求模块的代码转换为 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:请求失败,状态代码为 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 发布图像吗?

javascript node.js axios form-data node-request
2个回答
1
投票

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

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
库做了非常相似的事情。请参阅request.js


0
投票

vue3 与 laravel 10 项目发生同样的错误。

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***  

代码示例在这里, 员工.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>

EmployeeControler.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.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']);

上面的示例生成相同的错误,问题的根本原因是语法错误。我们可以像下面那样将其像素化,

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

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

© www.soinside.com 2019 - 2024. All rights reserved.