maneesha
maneesha

Reputation: 135

My POST request is working with Node.js but not with API

I am building a registration app using Nodejs and MySQL as the database. So when I run the script it gives the message 'registration successful' on the 'localhost:3000/register' and also the data is added to the table as well. But when I try to send data through API it gives me 'Cannot POST /register' this. I couldn't find an error in the code. Please Help Me with this.

I am using body-parser too in order to connect with the API requests. Also I use XAMPP. Here is my code;

const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const router = express.Router();
const bcrypt = require('bcrypt');
const saltRounds = 10;

// create connection to the database
const db = module.exports = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'pulse'
});

//connecting
db.connect((err) =>{
    if(err){
        throw err;
    }
    console.log('MySql connected...');
});

const app = module.exports = express();
app.use(bodyParser.urlencoded({extended: true})); //Accept  URL Encoded params
app.use(bodyParser.json()); //accept JSON Params

//create user Table
app.get('/createUser',(req,res)=>{
    let sql = 'CREATE TABLE users(id int AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), dateOfBirth VARCHAR(255), password VARCHAR(255), PRIMARY KEY(id))';
    db.query(sql,(err,result)=>{
        if(err) throw err;
        console.log(result);
        res.send('User table created');
    });

});

//register user
app.get('/register',(req,res,next)=>{

    const post_data = req.body;
    const name = post_data.name;
    const email = post_data.email;
    const dateOfBirth = post_data.date;
    const password = post_data.password;

    let userEmail = {'email':email};

    let sql =  'SELECT * FROM users WHERE ?';
    let query = db.query(sql,userEmail, (err,result)=>{
        if(err) throw err
            //console.log('[MySQL ERROR',err);
        if(result && result.length) {
            res.json('User already exists');
        }
        else{
            let insertUser = {'name':name, 'email':email, 'dateOfBirth':dateOfBirth, 'password':password};
            let sql = 'INSERT INTO users SET ?';
            let query = db.query(sql,insertUser,function(err,result){
                if(err) throw err;
                res.json('Registration successful');
            });
        }
    });   

});

//creating the server
app.listen('3000', () => {
    console.log("Server started on port 3000");
});

result of the local browser'localhost:3000/register' is "Registration successful" also a row is added to the table. bur in API,

<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /register</pre>
</body>
</html>

Upvotes: 0

Views: 238

Answers (3)

Junius L
Junius L

Reputation: 16152

You are sending a post request but your endpoint is get app.get('/register'), to make it a post change it.

app.get('/register') // this's get
//if you want to use it as post change it to 
app.post('/register', (req, res) => {...})

To send request to your endpoint, you either use a form like, as you can't access POST directly from your browser

<form action="/register" method="post">
 First name: <input type="text" name="fname"><br>
 Last name: <input type="text" name="lname"><br>
 <input type="submit" value="Submit">
</form>

or using jQuery post

$.post('/register', { name: "John", time: "2pm" }, (response) => console.log(response) );

Upvotes: 2

Sreehari
Sreehari

Reputation: 1370

You have to write a 'POST' endpoint to parse the request body.

app.get('/register',(req,res,next)=>{
    .....
    .....
})

Change the above to

app.post('/register',(req,res,next)=>{
    .....
    .....
})

Also, I don't think you can call 'POST' endpoint directly from a browser by simply calling the endpoint as localhost:3000/register. That will just call 'GET' endpoint. In order to test your POST api, either you have to create a form and make a POST call from it or use tools/google extension like "postman" to POST.

Upvotes: 2

Riajul Islam
Riajul Islam

Reputation: 1483

A have a little bit mistake on your post api. you declare `app.get('/register',(req,res,next)` as **get** method but it must be **post**. 

please copy the snipet bellow and run. Thanks

const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const router = express.Router();
const bcrypt = require('bcrypt');
const saltRounds = 10;

// create connection to the database
const db = module.exports = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'pulse'
});

//connecting
db.connect((err) =>{
    if(err){
        throw err;
    }
    console.log('MySql connected...');
});

const app = module.exports = express();
app.use(bodyParser.urlencoded({extended: true})); //Accept  URL Encoded params
app.use(bodyParser.json()); //accept JSON Params

//create user Table
app.get('/createUser',(req,res)=>{
    let sql = 'CREATE TABLE users(id int AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), dateOfBirth VARCHAR(255), password VARCHAR(255), PRIMARY KEY(id))';
    db.query(sql,(err,result)=>{
        if(err) throw err;
        console.log(result);
        res.send('User table created');
    });

});

//register user
app.post('/register',(req,res,next)=>{

    const post_data = req.body;
    const name = post_data.name;
    const email = post_data.email;
    const dateOfBirth = post_data.date;
    const password = post_data.password;

    let userEmail = {'email':email};

    let sql =  'SELECT * FROM users WHERE ?';
    let query = db.query(sql,userEmail, (err,result)=>{
        if(err) throw err
            //console.log('[MySQL ERROR',err);
        if(result && result.length) {
            res.json('User already exists');
        }
        else{
            let insertUser = {'name':name, 'email':email, 'dateOfBirth':dateOfBirth, 'password':password};
            let sql = 'INSERT INTO users SET ?';
            let query = db.query(sql,insertUser,function(err,result){
                if(err) throw err;
                res.json('Registration successful');
            });
        }
    });   

});

//creating the server
app.listen('3000', () => {
    console.log("Server started on port 3000");
});

Upvotes: 0

Related Questions