0
votes

I have been configuring my database that is linked with nodejs in the same folder, to be able to advance a little more as a programmer, and I try to make an ajax request to the database, but it gives me an error as if the database was off or the url was wrong

  POST http://localhost:3000/api/login 404 (Not Found)

This is the petition code

userLogin = (username, password) =>{
    const url = 'http://192.168.1.7:3000/api/login'
    console.log('hola')
    fetch('/api/login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({username: username, password: password})
    })
    .then(r => r.json())
    .then(data =>{
      if(data.status === 200){
        console.log('hola')
        this.setState({
          status: data.status,
          message: data.message,
          username: username
        })
        this.userSearch()
      }
    })
  }

Routes:

const express = require('express');
const api = express.Router();
const controllers = require('../controllers/controllers')
const cors = require('cors')



api.post('/register', controllers.registerUser)
api.post('/login', controllers.loginUsers)
api.get('/test',  controllers.test)

module.exports = api;

I have already made ajax requests before but the time I do it within the same node.js, if someone knows how to solve it please help me

1
I'm seeing 2 URLs in your code. Is your database API supposed to be exposed on http://192.168.1.7:3000 or http://localhost:3000? - nmina
If I use 2 but none makes the POST request, but trying a little more, and I see that another route than me to do tests I have that is type get if it worksIf I use 2 but none makes the POST request, but trying a little more, and I see that another route than me to do tests I have that is type get if it works - DansFuture
Where are you creating the server? - Mostafiz Rahman
Mern Stack, using react with nodejs inside my pc - DansFuture
I don't see where you defined the api/ prefix. Aren't the routes supposed to be e.g. /login instead of /api/login? - Jonas Osburg

1 Answers

0
votes
var app = express();
const controllers = require('../controllers/controllers')
const cors = require('cors')
var bodyParser = require('body-parser');
var port = process.env.PORT || 3013;

app.use(bodyParser.json());
app.use(cors(corsOption));

var server = require('http').Server(app);

server.listen(port, function () {
    console.log('Updated : Server listening at ports', port);
});

app.post('/api/register', controllers.registerUser)
app.post('/api/login', controllers.loginUsers)
aapppi.get('/api/test',  controllers.test)