Client side unable to hit its own server endpoint - javascript

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:
If I try to hit nodejs endpoint like this /api/soapAPIs/soapAPI, the browser shows pending request and it never goes to the server.
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":""}

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.

Related

GET Request repeatedly failed on the front end but not on backend

I'm working on a personal project that will allow users to find new books based on their preferences for the genre. The database I'm using is MongoDB. However, while I'm able to get all the data on the backend using Postman, I can't get it properly displayed on the frontend. At the moment, I'm just trying to get the data sent to the front end and at least console.log'd but it isn't making it that far.
Here is the code in the routes file.
router.get('/books/:genre', bookBuilder.get_some_books)
Here's the code on the backend that the routes file is pointing to and is working:
exports.get_some_books = async function (req, res) {
let { genre } = req.params;
try {
let books = await Book.find({"genre": genre});
if (books) {
res.json(books)
} else {
res.status(404).send({error: 'Not Found'});
}
} catch (err) {
res.status(500).send({error: err.message});
}
}
Here's my code on the frontend that is not working.
async getEverything() {
try {
let pbBooks = await axios.get(`/books/`, {
method: 'GET',
headers: {'Content-Type': 'application/json'},
params: {
genre: 'PB'
}
})
if (pbBooks) {
console.log(pbBooks)
} else {
this.$router.push('/Error');
}
} catch (err) {
console.log(`Network error: ${err.message}`)
}
}
My code stack is Vue.js, Express.js, Node.js and Axios. On the frontend, I've tried making the inner code of axios.get() into '/books/PB' and then tried getEverything(genre) along with /books/${genre} but neither seems to be working.
The error I am getting is a 404 Request Failed error that is from the catch block in the getEverything() function. I'm not sure why the frontend is unable to get the data when the backend works just fine. Is there anything I'm doing wrong?
404 is the HTTP status code for Not found, which implies there is no route setup on localhost for /books. Actually, /books would route to your app, not the backend (unless you have a proxy setup on your app server that redirects to the backend).
If a proxy were involved, it's likely misconfigured. Otherwise, the target URL in the Axios request should be <backend_url>/books (e.g., http://localhost:9999/books with the back running locally on port 9999, and the app on some other port).
Change
let pbBooks = await axios.get(`/books/`, {
...
to
let genre = "PB"
let pbBooks = await axios.get(`/books/${genre}`, {
method: 'GET',
headers: {'Content-Type': 'application/json'}
})
reason is the params part of the config object is converted to query strings (/books?genre=PB) instead of /books/PB, which is what the backend is expecting
More: https://masteringjs.io/tutorials/axios/get-query-params

Too many requests from nodejs server causes "connect EADDRNOTAVAIL"

In my Node server (running on Mac), I'm requesting data from an external API using websockets and sending the result I get to my cloud API.
The websocket is sending a lot of data (1000+ obj/s). When I try to POST this to my cloud server, I get error on client side (my node server). This only happens during high load, I get no errors when load is lower (say 300/s). I'm not POSTing to my local server so I don't know what this error means.
One thing I noticed is that the ports are not reused. When I have high load, I go up to 15000+ used ports on my local machine and then I start getting these errors.
I have tried setting "agent: false" in the HTTP header without success. I have also tried "connection": "keep-alive" without success (found these two suggestions on SO).
This is the code that is POSTing the data I get from websocket:
function PostCode(codestring, apipathstring) {
return new Promise((resolve,reject)=>{
// An object of options to indicate where to post to
var post_options = {
host: 'hostname', //
port: 'port',
path: apipathstring,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data),
}
};
// Set up the request
var post_req = https.request(post_options,function(res){
let data = '';
res.setEncoding('utf8');
// A chunk of data has been recieved.
res.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
res.on('end', () => {
resolve(data);
});
// Error event received
}).on("error", (err) => {
reject("POSTING Error: " + err);
});
post_req.write(post_data);
post_req.end();
})
}
Optimally, I would stream even high traffic data without getting these connection errors.
Errors below:
Error: connect EADDRNOTAVAIL [my_cloud_IP] - Local (0.0.0.0:0)
Error: getaddrinfo ENOTFOUND [my_cloud_IP] [my_cloud_IP]:[my_cloud_port]
You can create your own "keep alive" agent, and use that one specific agent to send all the HTTP requests:
const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
According to the document:
keepAlive Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection.

Fetch API Delay

I'm attempting to fetch data on my server using the fetch API for the request, but the request is taking FOREVER to process (it does eventually process). I'm using React as my view, and Express is serving up my pages. I've listed my Express and JSX code below. Any insight into why this may be happening (The 'mounted' message is logged immediately as expected, but the fetch API after delays) ?
Express:
app.use('/test',function(){
console.log('connected');
})
React.JS:
componentDidMount(){
console.log('mounted');
fetch('./test').then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
})
}
You have to send the response in the server side :
app.use('/test',function(request, response){
console.log('connected');
response.send(); //!!!!! this line
//Or: response.sendStatus(200); to send status code without body
});
... otherwise the endpoint will not be terminated.

Why does nodejs return 404?

I'm trying to create a custom module for a deployd backend to authenticate with the instagram api. The code is as follows:
var request = require('request');
var payload = undefined;
process.server.on('request', function(req, res) {
if (req.url === '/foo') {
function getPayload(callback) {
var code = req.headers.referer.substr(req.headers.referer.lastIndexOf('/') + 1);
request.post('https://api.instagram.com/oauth/access_token', {form:{
client_id: '****',
client_secret: '****',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:2403/auth/auth.html',
code: code
}},
function(error, response, body) {
var payload = JSON.stringify(body);
console.log(payload);
callback();
});
}
function setPayload() {
res.end(payload);
}
getPayload(setPayload);
}
});
I can console.log the response from the instagram server, but then when I try to write the response back to the client I get a 404 response. What am I missing? Sorry if this is a total noob question. That would be because I'm a noob. Thanks in advance.
Sorry for the lack of clarity. Edit for more info: I'm creating an endpoint at /foo with the above code. The client sends a GET request to /foo from a referring URL containing the Instagram access code. The server then POSTs the access code along with the other app-specific parameters to the Instagram server which returns an object containing an authorization token and information about the user. The 404 comes at the point where the client GETs /foo. My code successfully sends the access code to the Instagram server and returns the object containing the access token - this outputs on the console - but it won't write it back to the client, and the client gets a 404. Also, the 404 is returned to the client before the object returned by the Instagram server is logged in the console.

NodeJS HTTP request from AngularJS

I'm currently developing a web application using AngularJS on the fronted and NodeJS on the backend with express. I've had trouble requesting my backend API from the fronted however and hope you guys can help me.
Backend (NodeJS):
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
Frontend (AngularJS):
myApp.controller('myController', function($scope, $http) {
delete $httpProvider.defaults.headers.common["X-Requested-With"]
$http.get('http://localhost:5000/test').success(function(data) {
alert('Success')
}).error(function(data, status) {
alert('Error! ' + status + ' : ' + data)
})
})
When I refresh the app I get an alert saying: Error! 0 :, however, when I request the backend with curl or by the browser, I get the test dict back. The frontend seems to be able to access the backend though because I see it in my backend log that it's done a request and got something back, but firebug says that the response is empty, what should I do?
Thanks so much, let me know if you need more info from me.
Mattias
Make sure that your frontend and backend servers have the same origin (protocol, host and port). If not, then you does not recieve response since you make cross-origin ajax request. In this case you should send special header from your backend to allow it:
Access-Control-Allow-Origin: *
You can add response header with the following code:
res.set('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Origin', '*');
Use res.status(status).json(obj) instead of res.json(status, obj)

Categories

Resources