Not receiving GET response from Express server - javascript

When I send a GET req from my client to my Express server it sends the data to the client but I get an XMLHttpRequest ready state of 1 and a status of 0 and it never logs the response text.
Client:
req.onreadystatechange = function() {
console.log(this.readyState);
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
req.open('GET', url + 'users', true);
req.send();
Server:
app.get('/users', function(req, res) {
res.send(users);
});
If anyone can tell me why I can't receive the array of users on client side and how to fix it. That would be great.

First I would use fetch javascript because it looks more natural.
/* on server */
app.get('/users', function(req, res) {
res.send(users);
});
/* on client */
fetch('/users').then(async (response) => {
if (response.status === 200) {
console.log(await response.text());
// do you receive something ?
}
else {
throw new Error('something unexpected occurred');
}
}.catch(err => { console.err(err) })
If you don't receive anything, then you should check if your front page is served from the same data-providing server because when you call for /users the browser is prepending the host to the path. So if both your client page and your back server is not running on the same host it will fail.

Related

How to send data (a url string) in express to backend from frontend?

I am trying to build a wikipedia web scraper api and this is my code:
const app = express()
const port = 3000
const url = "https://en.wikipedia.org/wiki/Yeti_Airlines_Flight_691"
axios.get(url).then(async (res) => {
try {
if (res.status == 200) {
const result = // Doing cheerio stuff here
app.get('/', (req, res) => {
res.status(200).send(result)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
}
} finally {
//
}
});
How can I send url dynamically to backend using express and do some stuff then send result back to frontend?
Client side:
This is a function you define in your frontend. You set a request link, which must be known here on client side and server side. Thus take something like /request. Then use axios to send a request to the server. You can pass any parameters with „dynamic“ Information as you called it. The server will receive these informations and can handle them.
const getData = () => {
// insert your server url here instead, with the /request at the end
const requestLink = `http://localhost:3001/request`;
axios
.get(requestLink, {
params: { url: "wikipedia.de/test123" },
})
.catch((error) => {
// here you can implement error handling
console.log(error);
})
.then((res) => {
// print result, received from the server
console.log(res);
});
};
Server side:
The backend is going to wait for a request to the defined link /request.
If he receives such a request, he is executing the code. The req variable contains your dynamic data, such as the wiki url.
Use res.json to send data back to your frontend.
app.get(`/request`, (req, res) => {
// do something with the request here
console.log(req.query);
// send result to the frontend
res.json({
status: "This could be an answer to the frontend.",
});
});

Node JSON-Server returning MOCK post response

I'm trying to use https://www.npmjs.com/package/json-server as a mock backend, I'm able to match URLs for get, but how can i return some mock-response for POST calls.
Like for create user URL will be like
URL - http://localhost:4000/user
Method - POST
Request Data - {name:"abc", "address":"sample address"}
expected response -
httpStats Code - 200,
Response Data - {"message":"user-created", "user-id":"sample-user-id"}
In Some Cases I also want to send custom http codes like 500,423,404,401 etc.. depending upon some data.
Biggest problem is that my code is not returning anything response for POST, its only inserting records in JSON
By default POST requests through json-server should give a 201 created response.
If you need custom response handling, you might need a middleware to get hold of req and res object.
Here I'm adding a middleware to intercept POST requests and send a custom response. You could tweak it to your specific case.
// Custom middleware to access POST methods.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
Complete code (index.js)..
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
server.use(jsonServer.bodyParser);
server.use(middlewares);
// Custom middleware to access POST methids.
// Can be customized for other HTTP method as well.
server.use((req, res, next) => {
console.log("POST request listener");
const body = req.body;
console.log(body);
if (req.method === "POST") {
// If the method is a POST echo back the name from request body
res.json({ message:"User created successfully", name: req.body.name});
}else{
//Not a post request. Let db.json handle it
next();
}
});
server.use(router);
server.listen(3000, () => {
console.log("JSON Server is running");
});
And you can start json-server using node index.js

nodejs 400 bad request err. when sending form data via XMLHttpRequest().send

Im having trouble sending form data to my local NodeJS express server. I believe it has something to do with how I'm formatting my request. I am trying to register a new user account to a Postgresql database, using Passport as middleware, although I dont believe the code ever makes it that far.
Chrome DevTools Network Tab gives me additional info about the bad request
{"status":"Cannot read property 'length' of undefined"}
When a user hits 'Create Account', this code is fired off:
processForm(event) {
// prevent default action. in this case, action is the form submission event
event.preventDefault();
// create a string for an HTTP body message
const name = encodeURIComponent(this.state.user.name);
const email = encodeURIComponent(this.state.user.email);
const password = encodeURIComponent(this.state.user.password);
const formData = `name=${name}&email=${email}&password=${password}`;
// create an AJAX request
const xhr = new XMLHttpRequest();
xhr.open('post', '/auth/register');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
// success
// change the component-container state
this.setState({
errors: {}
});
// set a message
localStorage.setItem('successMessage', xhr.response.message);
this.setState({redirect: true});
} else {
// failure
const errors = xhr.response.errors ? xhr.response.errors : {};
errors.summary = xhr.response.message;
this.setState({
errors
});
}
});
xhr.send(formData);
}
Chrome DevTools flashes the 'xhr.send(formData)' as the first error in the stack.
This is the express handler code, but I don't think it ever makes it that far:
router.post('/register', authHelpers.loginRedirect, (req, res, next)
=> {
return authHelpers.createUser(req, res)
.then((response) => {
passport.authenticate('local', (err, user, info) => {
if (user) { handleResponse(res, 200, 'success'); }
})(req, res, next);
})
.catch((err) => { handleResponse(res, 500, 'error'); });
});
Any help would be greatly appreciated. I've spent hours trying to troubleshoot it. That's like every stackoverflow post ever.

Making multiple AngularJS Post requests to an Express Server? Server crashes on second post request

So given that I can't run these two post requests at the same time in my client, I'm trying to run the second post in the .then section of the first post. Which has always worked fine on my other projects. But for some reason when the second post request fires my server doesn't reply. When I check the console of the server, I notice it crashed and there's an error message (at the bottom of this post).
What could be causing this???
I have put breakpoints on the second post request in my server's code, and noticed the breakpoints don't even get hit. The server crashes before hitting and giving me the option to continue.
Client Code (gets fired when user presses a button):
$scope.searchCharacter = function(){
var request = {name: $scope.charName, realm: $scope.selectedRealm};
//First post request
$http.post('/searchCharacter', request)
.then(function(response) {
//sets some variables
var id = 0;
//Second post request
$http.post('/helloworld', id)
.then(function(response) {
//sets some more variables
debugger;
});
});
}
Server Code:
//First post request
app.post('/searchCharacter', jsonParser, function (req, res) {
blizzard.wow.character(['profile', 'stats', 'items', 'statistics'], { origin: 'us', realm: req.body.realm.name, name: req.body.name })
.then(response => {
if(response.status != 200){
res.send("That character doesn't exist! Please enter a valid character name.");
} else {
console.log(response.data);
res.send(response.data);
}
});
});
//Second Post Request
app.post('/helloworld', jsonParser, function (req, res) {
console.log(req.body);
res.send("hello");
});
Error message:
SyntaxError: Unexpected token #
at Object.parse (native)
at createStrictSyntaxError
(c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\lib\types\json.js:157:10)
at parse (c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\lib\types\json.js:83:15)
at c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\node_modules\raw-body\index.js:224:16)
at done (c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd
(c:\Users\RDubz\Documents\Interviews\EagleDream
12-7-17\Project\node_modules\body-parser\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
Try this:
$scope.searchCharacter = function(){
var request = {name: $scope.charName, realm: $scope.selectedRealm};
//First post request
$http.post('/searchCharacter', request)
.then(function(response) {
//sets some variables
var id = 0;
//Second post request (append id to route).
$http.post('/helloworld/' + id)
.then(function(response) {
//sets some more variables
debugger;
});
});
}
//First post request
app.post('/searchCharacter', jsonParser, function (req, res) {
blizzard.wow.character(['profile', 'stats', 'items', 'statistics'], { origin: 'us', realm: req.body.realm.name, name: req.body.name })
.then(response => {
if(response.status != 200){
res.send("That character doesn't exist! Please enter a valid character name.");
} else {
console.log(response.data);
res.send(response.data);
}
});
});
//Second Post Request (get id from req.params.id)
app.post('/helloworld/:id', function (req, res) {
console.log(req.params.id);
res.send("hello");
});
It appends id to the helloworld request, and defines a route helloworld/:id using req.params.id to pull the id out of the request.
Facepalm I was using var id = 0 and passing it to my function without realizing it needed to be passed as either an object or a param. Thanks to those who commented!

How to use a node.js back-end server to interact with the front-end and a mongolab database?

I am building a website with a simple jquery/html/css front-end and a node.js server back-end. If my front-end has a function to request a user's information from the server like so:
function requestUser(email, password) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:8888/getUser/" + email + "/" + password, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
xmlhttp.send();
}
and my node server looks like this:
var http = require("http"),
mongojs = require("mongojs"),
fs = require("fs"),
url = require("url");
express = require("express")
var server = http.createServer(requestHandler);
server.listen(8888);
var uri = "mongodb://<dbuser>:<dbpassword>#ds036698.mongolab.com:36698/alirodatabase";
var db = mongojs(uri, ["Papers", "Users"]);
console.log("node server running back end of app");
function requestHandler(request, response) {
//request for user is .../getUser/<username>/<password>
var path = url.parse(request.url).pathname;
var details = path.split('/');
if(details.indexOf("getUser") != -1) {
console.log("recieved request for user");
var user = db.Users.find({"email": details[details.indexOf("getUser") + 1],
"password": details[details.indexOf("getUser") + 2]});
user = user.toArray[0];
response.writeHead(200, {"Content-Type": "text/json"});
response.write(JSON.stringify(user));
}
else {
fs.readFile("./index.html", function(err, file) {
if(err) {
return
}
response.writeHead(200, {"Content-Type": "text/html"});
response.end(file, "utf-8");
});
}
}
why isn't it working? I get a 'mixed content' and/or 'corss-origin' error from firefox when I try to request from the server. How can I have the node server running in the same domain as the rest of the site to avoid these errors?
is really hard to read your code, I understand what you are trying to do, but let me suggest first a better structure easier to read, understand and implement more routes for your server, please check here:
var express = require('express'),
cors = require('cors'),
app = express();
app.use(cors());
app.get('/getUser/:user/:passwd', function(req, res, next) {
// Perform all mongo operations here using req.params.user and req.params.passwd
// and in the callback send a response like the object below
res.json({
msg: 'This is CORS-enabled for all origins!',
user: req.params.user,
passwd: req.params.passwd
});
});
app.listen(8888, function() {
console.log('CORS-enabled web server listening on port 8888');
});
Also the lack of CORS support (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) as you will need this in your use case for if you are planning to host serve static files consuming this service hosted in a different server, so lets use this module: https://www.npmjs.com/package/cors and it will allow express to process a request from anywhere.

Categories

Resources