could not get response from express.js server using postman - javascript

when i make post request from postman, the request data was shown server but server response i.e status code and json object was not send to postman, postman was just loading... and after some time it says could not get response from the server.
here is my server.js class
var bodyParser = require('body-parser');
var express = require('express');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {Users} = require('./models/Users');
var app = express();
app.use(bodyParser.json());
app.post('/todos', (req, res) =>{
var todo = new Todo({
text: req.body.text
});
todo.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.listen(3000, () =>{
console.log('started at port 3000');
});

There is some error in executing todo.save do console.log(e) to check what is the error throwing by mongo. Also you can send error in a response just to see what is going on, instead of writing res.status(400).send(e); write res.send(e) and it will send error as a response. "could not get response" error happens usually when you haven't send any response from the server. In your case you are sending response from your Promise resolved block but not from your error block.
Also make sure todo.save() return promise? may be you can achieve this by
todo.save(function(err,doc){
if(err){
return res.send(err);
}
res.send(doc);
})

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.",
});
});

Connect to mySql on VPS server eventhough works locally

I have a React front-end, with a Node back-end to connect to mySql for data. It works exactly how I want locally. However, now that I'm moving it to a VPS server, I can't seem to get my configuration correct.
The error I get is: create:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. It's actually returning HTML, of the page that says it's can't find the page.
I setup an express server with this code:(I do realize I need to move login details to an ENV file... just haven't yet)
const express = require('express');
const mysql = require('mysql2');
const connection = mysql.createPool({
host : 'localhost:3306',
user : 'root',
password : 'xxxxx',
database : 'ppr'
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.get('/api/clients/all', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'clients' table).
connection.query("SELECT * FROM clients", function (error, results) {
// If some error occurs, we throw an error.
if (error) throw error;
console.log(results);
res.json(results);
});
});
});
// Starting our server.
app.listen(3001, () => {
console.log('Listening on port http://localhost:3001');
});
I start this running on the server, and it runs. No errors.
But then my React app makes the first api call, and I get the error because it returns HTML instead of the data I'm expecting. Do I need to do something different to make it work in production? I have proxy setup in my local machine which probably makes it work... but what do I change for production?
Here's the API call that works locally, but not on the server if it helps:
componentDidMount() {
fetch('/api/clients/all')
.then(res => res.json())
.then((result) => {
this.setState({ clients: result });
console.log(result);
})
.then(
fetch(`/api/policy/all`)
.then(res => res.json())
.then((result) => {
this.setState({ policies: result });
console.log(result);
})
);
}

Receive Axios response from POST

I am trying to receive a response from my Node/Express server after making an Axios POST request.
I am able to successfully send a message to my server, where it is logged in console. I am trying to log the server response from my browser (using the code in axios.post.then() below). Any ideas why the response is not logging anything to the console?
-- client side --
<html>
<head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<button onclick="axiosPost()">Post Test</button>
<script>
function axiosPost() {
axios.post('http://localhost:3000/submitMessage', {
message: "sample message",
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
</script>
</div>
</body>
</html>
-- server side --
const express = require('express');
const app = express();
const port = 3000;
var path = require('path');
// serves index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
app.listen(port, () => console.log(`Listening at http://localhost:${port}`))
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.post('/submitMessage', function(request, response){
message = request.body.message;
console.log("Message: " + message);
response.send('Server response message!!');
})
listen to response.data in your front end. Or use simple response.end('Message') at your server side
Well I've never used Axios, but I think you need to return JSON
app.post('/submitMessage', (request, response) => {
message = request.body.message;
console.log("Message: " + message);
response.status(200).json({
status: 200,
ok: true,
data: {
msg: message
// Any data for the response
}
})
})
You can also use Async/Await on the front-end
There's a nice post here you can checkout about it
Looking back, my error was not realizing that there are two consoles: one for my client and one for the server. I was searching my server console for a message logged to my client console.
The message was ultimately being logged to my client console. Thanks to everyone who helped a beginner!

Return JSON from Express error handling middleware instead of HTML

I am having a bit of an issue returning a JSON response from my Express handling middleware. Currently, I am getting an HTML error page in Postman. On my actual client, I only return a 500 error from the fetch request in the console. The JSON data that should be the error message does not come through as anticipated.
Here is my error handling function. It simply passes the error as a JSON response back to the client. Anytime next(some_error) is called in my controller routes, Express pipes them through this error handling function:
const express = require('express');
const router = express.Router();
exports.errorHandler = (err, req, res, next) => {
res.setHeader('Content-type', 'application/json');
res.status(500).json({ err });
};
module.exports = router;
Here is a portion of the controller route that I am throwing an intentional error in to test the error handling middleware:
if (isMatch) {
const payload = { id: user._id };
jwt.sign(
payload,
JWT_SECRET_KEY,
{ expiresIn: 900000 },
(err, token) => {
if (err) {
const error = new Error(JWT_FAILED);
error.httpStatusCode = 400;
return next(error);
}
payload.token = `Bearer ${token}`;
return res.status(200).json({
success: true,
accountant: payload
});
}
);
} else {
const error = new Error(PASSWORD_INCORRECT);
error.genericError =
'The provided password did not match the database.';
error.httpStatusCode = 400;
return next(error);
}
This is the page I am getting in response for reference:
I am not sure what I am doing wrong, I usually don't have an issue sending a JSON response back from Express. I have a hunch the errors handled by Express require an extra step somewhere to not default to returning as HTML and not JSON.
This fixed my issue. I removed router and added module.exports = errorHandler and this resolved the issue. Express was not calling my errorHandler middleware function. It was just seeing a next(some_error) in my controller routes and then returning the error it's default way. I assumed my errorHandler function was returning this when in fact, my function was never even called.
This is the updated error handling middleware:
const errorHandler = (err, req, res, next) => {
res.json({ err: 'and error' });
};
module.exports = errorHandler;
This now sends back JSON. Phewwww.

Why does my $http.post return a 400 error?

I fairly new to MEAN, so sorry if this question is so obvious. I want to send an email to a contact when they click a send button. My code for handling a send email is using a post I am currently using a SendGrid Nodejs API to send the email. The problem is I keep running into a 400 Post Error.
This is the error I get in my Google Chrome Console
This is the error I get in my server terminal
This is in my controller.js:
$scope.send = function(contact) {
console.log("Controller: Sending message to:"+ contact.email);
$http.post('/email', contact.email).then(function (response) {
// return response;
refresh();
});
};
this code is in my server.js:
var express = require("express");
var app = express();
//require the mongojs mondule
var mongojs = require('mongojs');
//which db and collection we will be using
var db = mongojs('contactlist', ['contactlist']);
//sendgrid with my API Key
var sendgrid = require("sendgrid")("APIKEY");
var email = new sendgrid.Email();
var bodyParser = require('body-parser');
//location of your styles, html, etc
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.post('/email', function (req, res) {
var curEmail = req.body;
console.log("Hey I am going to send this person a message:" + curEmail);
var payload = {
to : 'test#gmail.com',
from : 'test1#gmail.com',
subject : 'Test Email',
text : 'This is my first email through SendGrid'
}
sendgrid.send(payload, function(err, json) {
if (err) {
console.error(err);
}
console.log(json);
});
});
Currently the email is hard coded but I will make the change after I fix the post issue. If you could point me in the right direction that would be very helpful. Thank you.
Looks like you're expecting the request body to contain JSON, with this line:
app.use(bodyParser.json());
Your error in your console says Unexpected token, which leads me to believe that body-parser encountered something it couldn't parse as JSON... probably a string. Which means that you sent your email as a string in the request body.
The easy fix would be to change how you're sending the request client-side:
var data = { email: 'some#email.com' }; // as opposed to just 'some#email.com'
$http.post('/email', data).then(refresh);
use this code
$scope.send = function(contact) {
console.log("Controller: Sending message to:"+ contact.email);
$http.post('/email', contact).then(function (response) {
// return response;
refresh();
});
};
and at server side
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser());

Categories

Resources