Home > OS >  im recieving a empty json object
im recieving a empty json object

Time:02-27

Im recieving a empty json object when posting to the route /api/register

with a JSON object of

{
    "username":"test2",
    "password":"1234567"
}
im 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")
})

frontend

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;

CodePudding user response:

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.

CodePudding user response:

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.)

  • Related