Transferring information to the server using a fetch request

Can anyone help me understand why the server is returning POST {} {} as empty objects after sending a request?

I'm confused about where this data has gone. Why did it disappear?

I'm completely lost on how to solve this...

index.js:

window.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector("form");

  form.addEventListener("submit", event => {
    console.log("it's activating");

    event.preventDefault();

    const name = document.getElementById("name").value;
    const password = document.getElementById("password").value;

    fetch("http:localhost:3000/register", {
      method: "POST",
      body: JSON.stringify({ name, password })
    })
      .then(res => {
        console.log(res);
      })
      .catch(error => console.log(error));
  });
});

//server.js:

const http = require("http");
const app = require("./app");

const port = 3000;

const server = http.createServer(app);

server.listen(port, () => {
  console.log("server activated");
});

//app.js

const loginRoute = require("./api/routes/loginRoute");
const registerRoute = require("./api/routes/registerRoute");
const verify = require("./autorization/verify");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use("/", (req, res, next) => {
  console.log(req.method, req.query, req.body);
  next();
});

app.use("/", loginRoute);

app.use("/", registerRoute);

app.use(verify);

Answer №1

From the image you provided, it appears there is a CORS problem. This can be resolved by implementing the https://github.com/expressjs/cors middleware.

var cors = require('cors');
app.use(cors());

Alternatively, you can enable CORS for specific routes only.

app.use('/', cors(), registerRoute);

Answer №2

registerRoute:

const express = require('express');
const router = express.Router();
const register = require('../../mongo/register');

router.post('/register',register);


module.exports = router;

register.js:

const mongo = require('./database');
const User = require('../api/patterns/user');


const register = (req,res)=>{

 const toSave = new User(req.body); 


 User.findOne({name: req.body.name},(err,name)=>{

  if(err) throw err;

  if(!name){


        toSave.save( (err)=> {

             if (err) throw err;
              console.log('user zapisany');

             });

   }else{
    console.log('juz taki istnieje');

  }

  });
};

app.js:

const loginRoute = require('./api/routes/loginRoute');
const registerRoute = require('./api/routes/registerRoute');
const verify = require('./autorization/verify');


var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/', (req,res,next)=>{console.log(req.method, req.query, req.body); 
next();});

app.use('/', loginRoute);

app.use('/', registerRoute);

app.use(verify);






module.exports = app;

It still keeps returning empty objects :(

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

The forEach function selectively bypasses certain objects during the iteration process

I have a task that involves writing a function to process an array of objects containing information and save that data in a JSON file. For instance: let arr = [ { creator: 'Girchi', title: ' ...

Unable to access CKEditor information from PHP using MySQL database

I need assistance, my database is not being updated even though there are no errors. Can someone please help me with this? Below is the code for faqs.php: <div class="myeditor"> <form method="post" action="insert.php"> FAQs & ...

Is the scrolling functionality acting strange while using React Three Fiber?

In my React Three Fiber application, I have the following structure: Website Canvas NativeHTMLContent Canvas Website The issue I'm facing is that after scrolling down the entire canvas, the scrollbar resets to the top and starts scrolling from the t ...

Storing data retrieved with Axios in Vuex state through a Vuex action

According to the Axios documentation, I am trying to simultaneously retrieve data from two sources on my backend (block.json and type.json) within the actions of my Vuex store. I have declared myBlocks and myTypes as data in my Vuex State. Although I am ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Troubleshooting Problems with CSS `transform` in JQuery UI's `Slide` Transition

While implementing JQueryUI's slide transition on an element with a CSS transform, I encountered an issue where the top half of the element gets hidden during the animation. Is there a way to tweak either my JQueryUI animation or CSS to avoid this pro ...

"Encountering a TypeError in Expressjs when attempting to call a function within a constructor from

I've encountered an issue while trying to call a function in the constructor from the prototype. The error message "TypeError: this.authorize is not a function" keeps popping up and I'm not sure what's causing it. TypeError: this.authorize ...

Guide to updating the favicon with next js

I am facing an issue where the favicon is not changing when searched on Google. The image is located in the public folder, but it is still showing the old logo instead of the new one. Below is the code from the _document.tsx file: <Html dir={dir}> ...

Creating lines in three.js with CanvasRenderer results in more fluid lines compared to WebGLRenderer

I'm facing a dilemma involving three.js where the CanvasRenderer renders lines much smoother than the WebGLRenderer. It seems like there is no antialiasing applied by the WebGLRenderer. When I refer to the three.js canvas - lines - random example fro ...

Having images that are too large in size and using a high percentage can

I'm encountering a strange issue. When I define the width and height of my images in pixels in my CSS file, all my jQuery animations and events work perfectly fine. However, when I switch to using percentages or 'auto' for the image dimensio ...

Consolidate multiple generic items into a single entry

In my current project, I am structuring the types for a complex javascript module. One of the requirements is to handle multiple types using generics, as shown in the snippet below: export interface ModelState< FetchListPayload, FetchListR ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

Commitment and the worth of pointing

I am trying to create a promise chain in Angular to execute a series of queries: for(variableIndex in _editableVariable.values) { var v = _editableVariable.values[variableIndex]; if(v.value != v.old_value) { ...

Encountering a blank page issue with react-router-dom v6 Routes

I am attempting to route a page to the root, but it keeps showing up as a blank page regardless of which JavaScript file I use. It seems like React Router DOM has been updated and no longer uses Switch. I haven't used React since last year, so I' ...

Delete any excess space that is currently covered by an image

While trying to implement a tab menu on my website by following this guide, I encountered an issue. The content box appears to be too long and is overlapping with the image. Can someone advise me on how to remove this extra space? For reference, you can v ...

Display the two values of an object pair using ng-repeat in AngularJS

I have an array of objects structured like this: myCtrl.siteNameLabels = myCtrl.actual.map(function (value, index) { return { actualSite: { actualSiteName : value, actualSiteData: myCtrl.tableData[index] }, ...

Challenges with resizing images in SVG using D3

I have an SVG image created using d3. I am facing an issue where the svg is extending beyond its parent div container. Here is the code snippet: <div id="test" style="{width: 500px; height:500px;}"> <svg></svg> </div> ...

Is there a way to verify the custom form when the braintree PayPal checkout button is clicked?

I am seeking a solution to validate a custom PHP form when the Braintree PayPal checkout button is clicked. Currently, the form redirects to the PayPal screen if it is not properly filled out. My goal is to prevent the PayPal popup window from opening if ...

Is it possible to utilize jQuery for dynamically generating a file along with its content?

Here is the HTML snippet I am working on: <ul> <li> Download <a href="#">file1</a> </li> <li> Download <a href="#">file2</a> </li> <li> Download <a href="#">file3</a> </li> ...

Introduction to Interactive HTML Pinball Game

As a beginner in the realm of computer science, I've recently embarked on creating a simple pinball game. My approach to maneuvering the flippers involves switching between images that depict the flipper in an upwards and downwards position by utilizi ...