0

I wrote a GET API that prints the parameter passed:

exports.agency_information = (req, res, next) => {
  console.log({param: req.params.usercode});
};

and this is the router:

const router = require('express').Router();

const AgencyController = require('../controllers/agency');

router.get('/:usercode', AgencyController.agency_information);

module.exports = router;

But I don't unsterstand why when I call the api this always return 200 OK and in Postman this is the return:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Fare la constatazione amichevole non è mai stato così facile" />
    <link rel="apple-touch-icon" href="logo192.png" />
    <link rel="manifest" href="/manifest.json" />
    <title>ConstaFAST</title>
    <link href="/static/css/2.0624914a.chunk.css" rel="stylesheet">
    <link href="/static/css/main.02a2fc0a.chunk.css" rel="stylesheet">
</head>

<body><noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script>
        !function(i){function e(e){for(var r,t,n=e[0],o=e[1],u=e[2],l=0,f=[];l<n.length;l++)t=n[l],Object.prototype.hasOwnProperty.call(p,t)&&p[t]&&f.push(p[t][0]),p[t]=0;for(r in o)Object.prototype.hasOwnProperty.call(o,r)&&(i[r]=o[r]);for(s&&s(e);f.length;)f.shift()();return c.push.apply(c,u||[]),a()}function a(){for(var e,r=0;r<c.length;r++){for(var t=c[r],n=!0,o=1;o<t.length;o++){var u=t[o];0!==p[u]&&(n=!1)}n&&(c.splice(r--,1),e=l(l.s=t[0]))}return e}var t={},p={1:0},c=[];function l(e){if(t[e])return t[e].exports;var r=t[e]={i:e,l:!1,exports:{}};return i[e].call(r.exports,r,r.exports,l),r.l=!0,r.exports}l.m=i,l.c=t,l.d=function(e,r,t){l.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},l.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},l.t=function(r,e){if(1&e&&(r=l(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var t=Object.create(null);if(l.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var n in r)l.d(t,n,function(e){return r[e]}.bind(null,n));return t},l.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return l.d(r,"a",r),r},l.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},l.p="/";var r=this.webpackJsonpwww=this.webpackJsonpwww||[],n=r.push.bind(r);r.push=e,r=r.slice();for(var o=0;o<r.length;o++)e(r[o]);var s=n;a()}([])
    </script>
    <script src="/static/js/2.9ed2bde4.chunk.js"></script>
    <script src="/static/js/main.ea8659b8.chunk.js"></script>
</body>

</html>

With or without any kind of paramater the result is the same.

SERVER CODE

const express = require('express');
const app = express();
const path = require('path');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config()

const agencyRoutes = require('./api/routes/agency');
const companyRoutes = require('./api/routes/company');

const port = process.env.PORT || 3000;

mongoose.connect(process.env.DB_CONNECT, {
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true
}, () => console.log('Connect to the database'));

mongoose.Promise = global.Promise;

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use( (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );

  if ( req.method === 'OPTIONS' ) {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});
  }

  next();
});

app.use(express.static(path.resolve(__dirname, '../www', 'build')));
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../www', 'build', 'index.html'));
});

app.use('/api/agency', agencyRoutes);
app.use('/api/company', companyRoutes);

app.use( (req, res, next) => {
  const error = new Error('Not found');
  error.status = 404;
  next(error);
});

app.use( (error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

app.listen(port, () => console.log(`Server up and running on port ${port}`));
th3g3ntl3man
  • 1,926
  • 5
  • 29
  • 50

2 Answers2

1

First of all send response from the server.

exports.agency_information = (req, res, next) => {
    console.log({param: req.params.usercode});
    res.send('send something from server');
};

Now from the postman call your api

for example using this

http://localhost:3000/api/agency/1234

Here above: replace yourportnumber with the port on which your server is running. And 1122 is the parameter that you are sending and it prints in console.

If this is your default route then its called and you see the response in postman and parameter prints in console.

UPDATE Your SERVER Code move the api routes up app.get(*) must be last. You getting html page in postman because of this.

Here's the updated server code

const express = require('express');
const app = express();
const path = require('path');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config()

const agencyRoutes = require('./api/routes/agency');
const companyRoutes = require('./api/routes/company');

const port = process.env.PORT || 3000;

mongoose.connect(process.env.DB_CONNECT, {
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true
}, () => console.log('Connect to the database'));

mongoose.Promise = global.Promise;

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use( (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );

  if ( req.method === 'OPTIONS' ) {
    res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});
  }

  next();
});

app.use('/api/agency', agencyRoutes);
app.use('/api/company', companyRoutes);

app.use(express.static(path.resolve(__dirname, '../www', 'build')));
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../www', 'build', 'index.html'));
});

app.use( (req, res, next) => {
  const error = new Error('Not found');
  error.status = 404;
  next(error);
});

app.use( (error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

app.listen(port, () => console.log(`Server up and running on port ${port}`));
Arslan Razzaq
  • 193
  • 1
  • 1
  • 10
  • Yes, but the problem persist! The `res.send('send something from server');` doesn't resolve the problem! – th3g3ntl3man Nov 08 '19 at 18:50
  • Can you show me how you call the API from the Postman? And also show code where you call this router. – Arslan Razzaq Nov 08 '19 at 19:46
  • This is the Postam call `http://localhost:3000/api/agency/1234` with `GET` method. I just update the answare with che code of the server. – th3g3ntl3man Nov 08 '19 at 20:06
  • 1
    Check out the updated answer you get this issue because of app.get(*) route first. Which receive all the get requests and fulfill them. – Arslan Razzaq Nov 08 '19 at 21:06
0

It seems like this may be the default page for your application even if nothing is passed. You said regardless of parameter your output is the same. It seems like you are stuck outputting a default page. Which makes sense because the Italian says "Fare la constatazione amichevole non è mai stato così facile" Making a friendly statement has never been easier. I would check the default setting check to see if you can get java script to allowed and then check to see if it works.

because this is javascript you might have something stopping java script from allowing this to work and this could be the default page when your java script doesn't work.

exports.agency_information = (req, res, next) => {
  console.log({param: req.params.usercode});
};

You can try using to check to see if js is disabled as well.

How to check javascript is enabled or not in Node JS server side code <noscript> <meta http-equiv=refresh content='0; url=http://your.domain/noscript' </noscript>

Michael Hearn
  • 557
  • 6
  • 18