Client side unable to hit its own server endpoint

Issue

I’ve a AngularFullStack project in which I’m trying to hit my project’s server endpoint using the following code, however the problem is the call isn’t going through from angular client side to the nodejs server. Since it’s my first project, I’ve little to no idea what might be going wrong that might be causing this weird conflict.

ClientSide:

$http({
        method: 'POST',
        url: '/api/soapAPIs/soapAPI',
        data: request,
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(function(response) {
        console.log("response from server is: ", response);
      })
      .catch(function(error) {
        console.log("error in calling server is: ", error);
      });

I have installed CORS on server side and wrote the following code in app.js but still it doesn’t work.

Server App.js

// Setup server
var app = express();
var cors = require('cors');
//add cors to do the cross site requests
app.use(cors());

Server Endpoint Code:

export function soapAPI(req, res) {
  console.log("SERVER SIDE ", req.body);
  res.status(statusCode).json({"status":"success"});
  res.send();
}

Following are the problems:

  1. If I try to hit nodejs endpoint like this /api/soapAPIs/soapAPI, the browser shows pending request and it never goes to the server.

  2. When I add the full classified url for the endpoint like this http:localhost:9000/api/soapAPIs/soapAPI, it hits the endpoint but then the client never receives response from the server. I don’t want to provide the full classified URL on the client side for obvious reasons.

How can I resolve this issue? Please let me know if you need any other code/information.

EDIT:

By using full classified path, the server endpoint gets hit but its response is never received by the client side. I get this error in browser:

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/things","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}

Solution

Uncomment the following line:

/*mongoose.connect(config.mongo.uri, config.mongo.options);
  mongoose.connection.on('error', function(err) {
  console.error(`MongoDB connection error: ${err}`);
  process.exit(-1); // eslint-disable-line no-process-exit
});
*/

Basically this is causing your controller to not return any response because your mongoose models are being referenced but the connection to mongo fails.

Answered By – aliirz

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.