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

Issue

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;

Solution

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

Leave a Reply

(*) Required, Your email will not be published