Express node.js api app.post does work for / but not with /path

Viewed 146

I am new at Node.js and trying to make an API that will do CRUD operations in sql server. The problem for me is that I can get the data but cannot post it, and get the error "cant get /". I know there are similar questions about this subject but nothing works for me so I thought maybe my code has different kinds of error. Any help will be appreciated and save my life in a way. Also, this is my first question on stackoverflow, sorry for the possible mistakes..

Here is the server.js

const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect') 
const app = express();

app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true })); 


app.get("/test", (req, res, next) => {
    new sql.ConnectionPool(sqlConfig).connect()
        .then(pool => {
            return pool.query('select * from tblProfile')
        })
        .then(result => {
            res.send(result);
        })

})
app.post('/test', (req, res) => {
    let name = req.query.name;
    let lastname = req.query.lastname;
    let email = req.query.email;
    let password = req.query.password;
    let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
    conn.query(sql, [name, lastname, email, password], (err, result) => {
        if (err) throw err;
        res.write("inserted.");
        res.end();
    });

    app.listen(port, () => {
        console.log("working: " + port)
    })
});

This is the connect.js

   

var sqlConfig = {

    server: '192.168.1.2',
    database: 'profile',
    user: 'username',
    password: 'user',

};

module.exports = sqlConfig;

2 Answers

This is happening because you aren't responding or sending anything to that route

So if you want to get rid of the error Run

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

But if you want to send a static file to the route Create a folder call public * note it can be anything

And type

var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));

Then you can access code in the dir

And as for the writing I think you should try this

app.post('/test', (req, res) => {
    let name = req.body.name;
    let lastname = req.body.lastname;
    let email = req.body.email;
    let password = req.body.password;
    let sql = "INSERT INTO tblProfile(name,lastname,email,password VAUES(? ? ? ?)";
    conn.query(sql, [name, lastname, email, password], (err, result) => {
        if (err) throw err;
        res.write("inserted.");
        res.end();
    });

Change query to body Since you installed body-parser

Taking a quick look over your code, the only issues I can see are in your query to submit the data. Within your query statement, I added a closed parentheses after the variables to be entered into the database and made a typo correction to the word Values. I also changed up how the data is retrieved from req.query to destructure it and simply the code a bit. Based on everything else I saw, and the fact that you are able to get data from the database, this should work out fine. If it doesn't, I would recommend inserting some console.log() statements in the post query to see where it might be having issues and why. For example, you could run console.dir(req.query); in your post route to see what data is actually coming from the req and make sure it is all there. If something is missing, then the query won't actually execute. If this doesn't work, let me know, along with the information from any console logs you did and I'll take another look at it.

const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect') 
const app = express();

app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true })); 


app.get("/test", (req, res, next) => {
    new sql.ConnectionPool(sqlConfig).connect()
        .then(pool => {
            return pool.query('select * from tblProfile')
        })
        .then(result => {
            res.send(result);
        })

})
app.post('/test', (req, res) => {
    //console.dir(req.query);
    let {name, lastname, email, password} = req.query;
    let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
    conn.query(sql, [name, lastname, email, password], (err, result) => {
        if (err) throw err;
        res.write("inserted.");
        res.end();
    });

    app.listen(port, () => {
        console.log("working: " + port)
    })
});

Related