I send as POST method the temperature of my DEVKIT SigFox, but I have the error "Cannot Get /end-point" on my Node JS server

52 Views Asked by At

In the following Node JS code:


import express from "express";
import pg from "pg";
import cors from "cors";
import bodyParser from "body-parser";
import { PORT, DB_USER, DB_HOST, DB_NAME, DB_PASS, DB_PORT } from "./config.js";

const { Pool } = pg;

const app = express();

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

const pool = new Pool({
  user: DB_USER,
  host: DB_HOST,
  database: DB_NAME,
  password: DB_PASS,
  port: DB_PORT,
});

app.get("/", async (req, res) => {
  const result = await pool.query(`SELECT * FROM usuarios;`);
  const rows = result.rows;
  res.json(rows);
});

app.post("/sigfox", (req, res) => {
  res.json(req.body);
  res.sendStatus(200);
});

app.listen(PORT, () => {
  console.log(`Servidor iniciado en http://localhost:`, PORT);
});

I am trying to send the temperature of my "SigFox DEVKIT" by POST method to the server, but when I enter the server I get the error "Cannot GET /sigfox".

But in the Sigfox Backend CallBack he tells me that he sent the data correctly.

[SigFox] CallBacks Results --> https://i.stack.imgur.com/tFJqv.png

I don't know why this happened. I show you my Callback Settings in case I have something wrong.

[SigFox] CallBack Settings --> https://i.stack.imgur.com/92DGL.png

Why did that happen and how can I solve it?

Previously I thought it was because I was working with a local server, but now with a hosted server I get the same error. Please, I need help.

1

There are 1 best solutions below

6
hcheung On

There are two problems with your nodejs code:

  1. Your image shows that the client is sending a POST request, while your nodejs only has a route for handling Get request.
  2. The POST request from the client has a Content-Type of x-www-form-urlencoded, but your nodejs is trying to parse the data as json format with app.use(bodyParser.json());.

Here is the minimum code that should work as per your client's POST request:

import express from "express";

const PORT = 3000;
const app = express();
app.use(require('body-parser').urlencoded({ extended: false }));

app.get("/", (req, res) => {
  res.send('GET request to the server');
});

app.post("/sigfox", (req, res) => {
  res.send(res.json(req.body)); //send a response as json with req.body
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:`, PORT);
});