RainyPlays
RainyPlays

Reputation: 25

im recieving a empty json object

I'm receiving an empty JSON object when posting to the route /api/register

with a JSON object of

{
    "username":"test2",
    "password":"1234567"
}

I'm trying to console.log the req.body

const UserModel = require("./Server/models/User")
const Post = require("./Server/models/Post")
const bodyParser = require("body-parser")
const express = require("express")
const app = express()

app.use(express.json())

app.get("/",(req,res)=> {
    res.send("Home")
})

app.get("/api/register",(req,res)=> {
    res.send("register")
})


app.post("/api/register",(req,res)=> {
    console.log("recieved")
    console.log(req.body)
})




app.listen(3001,()=> {
    console.log("listening on port 3001")
})

Front-end

import React, { useState } from 'react';
import './App.css';

function App() {
const [username,setUsername] = useState("")
const [password,setPassword] = useState("")


function handleSubmit(event) {
event.preventDefault
fetch("http://localhost:3001/api/register",{
  method:"post",
  headers:{
    "Content-Type" : "application/json"
  },
  body:JSON.stringify({username:username,password:password})
})


} 



  return (
    <div className="App">
      <form onSubmit={handleSubmit}>

        <input placeholder="username" value={username} onChange={ e => setUsername(e.target.value)} />
        <input placeholder="password " value={password} onChange={ e => setPassword(e.target.value)}/>
        <button  type='submit' >Submit</button>
      </form>
    </div>
  );
}

export default App;

Upvotes: 0

Views: 852

Answers (2)

fgenz
fgenz

Reputation: 41

Seems like you are not sending anything from your API. You can use .send() function to send data back to the caller. Also, please edit the question and specify where do you expect json printing (console, webpage etc.)

Upvotes: 1

Shivam Mishra
Shivam Mishra

Reputation: 113

You are not sending back anything from post endpoint. You should do it like this.

app.post("/api/register",(req,res)=> {
    console.log("recieved")
    console.log(req.body)
    res.send(req.body);
});

In this case we send back the data that user sends.

Upvotes: 1

Related Questions