Encountered a server issue (500 Internal Server Error) when attempting to send a POST

I have been working on a social media app project using React and MongoDB. However, every time I try to register a user, I encounter a POST error in the console. I have reviewed both my client-side and server-side code, but I am still unable to successfully post and register user information.

**EDIT ** Thank you for the guidance on how to improve the question. Here is my revised attempt at making a clearer post:

The primary error appearing in the console is as follows:

> POST http://localhost:3001/auth/register 500 (Internal Server Error)
> register @ Form.jsx:56
> handleFormSubmit @ Form.jsx:89

Upon further investigation of the error in the browser console, it has led me to this line of code in my Form.jsx file:

const savedUserResponse = await fetch("http://localhost:3001/auth/register", {
      method: "POST",
      body: formData,
    });

This snippet displays the complete function block for my register functionality:

const register = async (values, onSubmitProps) => {
    const formData = new FormData();
    for (let value in values) {
      formData.append(value, values[value]);
    }
    formData.append("picturePath", values.picture.name);

    const savedUserResponse = await fetch("http://localhost:3001/auth/register", {
      method: "POST",
      body: formData,
    });
    const savedUser = await savedUserResponse.json();
    onSubmitProps.resetForm();

    if (savedUser) {
      setPageType("login");
    }
};

In my server-side code, here is the index.js responsible for handling authentication:

// ROUTES WITH FILES
app.post("/auth/register", upload.single("picture"), register);
// more routes...

// ROUTES
app.use("/auth", authRoutes);
app.use("/users", userRoutes);
app.use("/posts", postRoutes);

// MONGOOSE
const PORT = process.env.PORT || 6001;
mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => {
    app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
}).catch((error) => console.log(`${error} did not connect`));

Below is the register function from my auth.js located in the controllers folder:

export const register = async (req, res) => {
  try {
    // User registration logic...
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

The server response I receive reads:

"POST /auth/register HTTP/1.1" 500 248
Error: ENOENT: no such file or directory, open 'G:\WebDev\DesTracker\destracker-app\server\public,assets\p2.jpeg'

After clicking on the register button, I expect user details to be posted to the database, but instead, I am facing an internal server error 500.

Answer №1

In order to receive the most accurate answer, it would be helpful to provide additional information as suggested by @Yarin_007. Nonetheless, I will do my best to offer some assistance based on the limited details provided.

A status code of 500 typically indicates that there is an exception or error occurring on your server. The warning you received should specify where the error is located, why the error is occurring, and what exactly the error entails.

The specific location of the error can be found within the submitForm() function.

Regarding the nature of the error, it appears to be a SyntaxError, indicating that there may be a deviation from the correct syntax of a programming language in your code.

The reason for this error seems to be related to invalid JSON formatting containing characters like '<' and '"<!DOCTYPE "...'

This explanation is based on the information provided. If you can share more details about the error, we can offer further help.

Wishing you success with your coding endeavors!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the onclick event to not function properly when called from an external .js file?

I've created a .js file that contains code for a photo album application. The file includes functions for changing images when buttons are clicked. However, when I interact with the buttons, the images do not change as expected. The code in the .js f ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Tips for showing various column information as tooltips in ag grid's pivot mode

var ColumnDefinitions = [{ headerName: "Column A", field: 'colA', rowGroup: true }, { headerName: "Column B", field: 'colB', pivot: true, enablePivot: true }, { headerName: "Column C", field: ...

I am unable to enter any text in an angular modal

Currently, I am facing an issue where I am unable to click on the search input field within a modal. The goal is to implement a search functionality in a table displayed inside a modal window. The idea is to have a list of hospitals where users can view d ...

How can I easily activate a C# class from an asp.net webpage?

I have three labels in my asp.net page: One with a default name for filtering Another filled with a list of names to click on for new filter A third one with a list of items to be filtered The content of the second and third labels is loaded by C# code ...

"Jquery with 3 buttons for toggling on and off individually, as well

There are 3 buttons available: button 1, button 2, and button 3. Button 1 toggles the show/hide functionality of the left side, button 2 does the same for the right side, and button 3 affects both sides simultaneously. What is the best approach to achieve ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Automating Internet Explorer using VBA to click a button

I'm currently working on automating tasks on a website using VBA, specifically an online banking system where I am trying to export Transaction History data into a .csv file. Everything seems to be running smoothly until I reach the final Export butto ...

Angular connecting to the count of filtered items

Here's the array I'm working with: [ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

I am receiving a high volume of row data from the server. What is the best way to present this information on a redirected page?

There is a scenario where Page 1 receives a substantial amount of row data in JSON format from the server. The goal is to present this information on Page 2, which will be accessed by clicking on Page 1. To accomplish this task, JavaScript/jQuery and PHP ...

Expanding a table by including a new column using Node.js and Knex

Currently building a service for my router using Node.js and Knex, but I'm struggling to add a column to an existing table. Any assistance would be greatly appreciated. Even though I am working with PostgreSQL, I believe the solution will be similar r ...

Understanding how to read a JSON response when the dataType is specifically set to JSONP

I am attempting to send a JSONP request for cross-domain functionality. The issue is that my server does not support JSONP requests and interprets them as regular JSON, responding with an object: {result: 1} Below is the AJAX request I have made: jQuery. ...

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...

PHP: Safely Submitting Scores Using JavaScript

I have developed a PHP file that updates scores in a database. For example: http://domain.com/heli/test.php?id=100001181378824&score=50000 The code in test.php is as follows: mysql_connect(localhost,$user,$password); $id = mysql_real_escape_string($_ ...

Discover the capability to choose dates from different months using the DatePicker component from @material-ui/pickers

I am currently in the midst of a React project that requires the use of the DatePicker component from @material-ui/pickers. The specific mandate is to show dates outside of the current month and allow users to select those days without needing to switch m ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...