Reputation: 23
I am trying to convert the below code which is using request module to axios module to send the POST request.
request module code:
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");
});
The above code works fine and the image is posted successfully with the request module. But when I convert the same to axios, I am getting a 500 Error. (AxiosError: Request failed with status code 500)
axios module code:
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);
});
Can anyone find out what I am doing wrong here?
Is there any other way to post the image using axios other than using form-data?
Upvotes: 2
Views: 12599
Reputation: 1
Same Error occured vue3 with laravel 10 project.
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***
Code sample here , 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>
EmployeeControler.php class , <?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 here <?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']);
Above egsamples generate same error ,root cause of the problem is syntax error.we can fix it as like follwed ,
$employees->callingname = $req -> callingname;
$employees->nic = $req -> nic;
we want to use correct syntax to resolve above problem use -> insted of .(dot)
Upvotes: 0
Reputation: 164813
See the documentation for FormData#append(). You can provide extra data like the file name as the 3rd options parameter
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(),
},
});
Under the hood, request()
does something very similar with the exact same form-data
library. See request.js
Upvotes: 1