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 the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Opting for a .catch over a try/catch block

Instead of using a traditional try/catch to manage errors when initiating requests like the example below: let body; try { const response = await sendRequest( "POST", "/api/AccountApi/RefundGetStatus", JSON.stringify(refundPara ...

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Creating a static Top Bar that remains unaffected by page refreshing using Ajax or any other method can be achieved by implementing JavaScript and CSS

I've designed a sleek top bar for my upcoming website project. Below is the CSS code snippet for creating this clean div bar: .topbar { display:block; width:100%; height:40px; background-color:#f5f5f5; } I'm looking to incorporate a simple .SWF ...

Having trouble with NodeJS API loop or error handling: MySQL pool connections not closing properly?

Experimenting with my initial API NodeJS application. The current configuration for MYSQL is as follows: const mysql = require('mysql'); var pool = mysql.createPool({ host:'localhost', user: 'abc', password ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

Refresh the webpage source code for an AJAX request

When using AJAX calls on a page, I have noticed that the page source remains unchanged. This can be problematic if a user performs forward/backward operations in their browser, as the browser will display the original HTML code instead of the updated conte ...

Encountering Error with Axios in Nuxt while Navigating Pages

Working on a nuxt application utilizing axios for API calls. In my index.vue file, I have the code snippet below. <template> <div> <Hero /> <Homebooks :details="details" /> </div> </template> <s ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

Steps to transfer selected autocomplete value ID to data attribute using jQuery

I am working on a project where I need to store the State ID in my database instead of the State Name. Currently, I am using an autocomplete query to select the State. How can I pass the selected State's respective ID to the data-attribute of the inpu ...

Fetching user feeds from Facebook with AngularJS is easier than you think

I have searched through multiple articles but have yet to find a solution for this particular issue. My goal is to retrieve user feeds from Facebook. How can I achieve this? Below is my code: var newMod = angular.module('newapp', []); newMod.c ...

Tips on how to collapse all elements whenever one is being opened in a FAQ card using ReactJS

Clicking on a question reveals its text, and clicking on another collapses the previous one. The issue arises when trying to close an open question by clicking on it again - it doesn't work as intended due to a potential error in the If statement [im ...

Is there a way to modify the background color of ::before when hovering over it?

I have a ul-li list and when i hover last li ::before element looks white and not so good. I want to change it when i hover the last li element. How can I achieve this? Here are my codes: <div className="dropup-content"> <ul> & ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Position the text alongside the thumbnail rather than in the center

In the current setup, my username text is positioned in the center of the view. I want to reconfigure it so that it displays directly to the right of the thumbnail. However, removing the alignItems: 'center', property from the item disrupts the e ...

React-Native-SVG encountered an error: Invariant Violation - the component "RNSVGGroup" could not be found in the UIManager

Trying to create an SVG in React-Native using react-native-svg. I have set up a React-Native-CLI. After doing some research, I attempted to solve the issue on my own and found something useful. I tried running cd ios && pod install. I wasn't ...

Is there a way to modify the domain of an iFrame's scr based on the parent window's URL?

Is there a way to dynamically change the scr="" attribute of an iFrame based on the current URL of the window? The goal is to have different values for the scr attribute depending on the parent window's URL. For example, if the parent window's UR ...

Handling routerLink exceptions in Angular 2, 4, and 5

In my app, I am working on catching routing exceptions. There are three ways in which a user can navigate: If the user types the address directly - this can be caught easily by using { path: '**', redirectTo: 'errorPage'} in the route ...

limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once. const main = async () => { items.forEach(async (i: Item) => ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...