Home > Net >  How to get Angular form data to show in JSON format in localhost server
How to get Angular form data to show in JSON format in localhost server

Time:07-23

I'm new to Angular so I've been reading the documentation, watching Youtube tutorials, and reading other StackOverflow posts but I seem to be getting nowhere when I try to get my data to post to the localhost server.

I am creating a simple sign-up form. User inputs their email, username, and password.

This is signup.component.html

<div>
<fieldset>
    <form #login = ngForm (ngSubmit)="addUser(login)" method="post">
        <label>
            Email
        </label>
        <input type="text" name = "email" ngModel>
        <br>
        <label>
            Username
        </label>
        <input type="text" name="username" ngModel>
        <br>
        <label>
            Password
        </label>
        <input type="password" name="password" ngModel>
        <button type="submit">
            Sign Up
        </button>
    </form>
    
    <br>
    <a href="/login">
        <span>Login</span>
    </a>
    <br>
    </fieldset>
</div>

This is my signup.component.ts

import { Component, OnInit } from '@angular/core';
import { UserInfoModel } from '../userInfoModel';
import {HttpClient, HttpClientModule, HttpHeaders} from '@angular/common/http'
import { Observable } from 'rxjs';


import { catchError, map, tap } from 'rxjs/operators';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['../form/form.component.css']
})
export class SignupComponent{

  user: UserInfoModel = new UserInfoModel("[email protected]", "admin", "password",0,["tst",0,0]);
  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json','Access-Control-Allow-Origin': '*', })
  };
  constructor(private http: HttpClient) { }

  addUser(login:any){
    console.log(JSON.stringify(login.value));

    return this.http.post<any>('http://localhost:3000/signup', JSON.stringify(login.value)).subscribe(data => {
      data = this.user;
  })
  }
}

This is my index.js

var  use = require('./user')

const express = require('express')
const app = express()
let cors = require("cors");

app.use(cors());

app.get('/', (req, res) => {
  res.send('hello world');
})

app.get('/signup', (req, res) => {
  res.send("hello");
})


app.post('/signup', (req, res) => {
    res.send(req.query);
    console.log(req.query)
    console.log("reached server");
    
  })

  app.listen(3000,() => console.log("Hello World!"))

Angular runs on PORT 4200. Server runs on PORT 3000

Now here's the issue, if you look at signup.component.ts...

When I run console.log(JSON.stringify(login.value));: I get the proper JSON values. Which outputs to {"email":"[email protected]","username":"admin","password":"adminPassword"}. This is what I want to receive on the server

When I run return this.http.post<any>('http://localhost:3000/signup', JSON.stringify(login.value)).subscribe(data => { data = this.user; }) } It hits the server but returns a req.query of {}.

I used Postman to make sure everything is working properly and Postman returns proper JSON data. From researching, this is because Postman uses a different method to send data or something like that.

Feedback on what I'm doing wrong would be greatly appreciated. I feel as though it shouldn't be this hard to get my data to send.

CodePudding user response:

After getting some help from the people here and another person on Reddit, I was able to finally realize what I did wrong.

As @RichardoMachado mentioned, I needed to remove my JSON.stringify. I changed

    return this.http.post<any>('http://localhost:3000/signup', 
    JSON.stringify(login.value)).subscribe(data => {
    data = this.user;
     })

to

    return this.http.post<any>('http://localhost:3000/signup', 
    login.value).subscribe(data => {
    data = this.user;
     })

As @Gopal mentioned, I needed to use req.body for a post call, so I changed my index.js file. I changed req.query to req.body. See below for example.

    app.post('/signup', (req, res) => {
    res.send(req.body);
    console.log(req.body)
    console.log("reached server"); 
     })

Lastly, I didn't have the express body-parser installed. So I ran npm install body-parser in my server terminal and I added this to my index.js.

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

Without this, I was getting "undefined" when I sent form data to the server.

  • Related