Unable to access API created on local node server - javascript

I created a simple API on a node server. The server is running on the port 9000. I created an endpoint called getUserDetails and I'm passing a simple object. The problem is I can access the API from the browser by entering the full URL 'http://localhost:9000/getUserDetails'.
But I cannot access the API in another HTML file. To elaborate, I created a simple HTML file to test out this API.
My node server:
const app = express();
app.get('/getUserDetails', (req, res) => {
res.send({
firstname : 'Giri',
secondname: 'Aakula',
dob: '15-09-1997',
age: 22,
qualification : 'Graduate',
status : 'pass'
})
})
app.listen(9000);
My HTML file
<!DOCTYPE html>
<html>
<head>
<title>Test page</title>
<style>
h1{
font-size: 50px;
}
</style>
</head>
<script>
fetch('http://localhost:9000/getUserDetails')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
</script>
<body>
<h1>This is a test page</h1>
</body>
</html>

I forgot to add cors. By adding this one line fixed my issue.
const express = require('express');
const app = express();
app.get('/getUserDetails', (req, res) => {
//this is the updated line
res.setHeader('Access-Control-Allow-Origin', '*');
res.send({
firstname : 'Giri',
secondname: 'Aakula',
dob: '15-09-1997',
age: 22,
qualification : 'Graduate',
status : 'pass'
})
})
app.listen(9000);

Related

Not able to add another JSON object while checking this API in Postman

I was trying to put another JSON object through Postman in an API that I have built.
It was a tutorial from Mosh Hamedani's YT channel where he was teaching about how to make a API using Node.js, Express and Postman.
Throughout the video everything he showed worked pretty good, but only in this section this code is not able to take a POST request in Postman.
As soon as I select Body > Raw and send the request after pasting the localhost URL in postman, it is coming up with an error.
The whole thing is mentioned underneath.
This is the code for the API
`const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: 'courses1'},
{ id: 2, name: 'courses2'},
{ id: 3, name: 'courses3'},
];
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/api/courses', (req,res) => {
res.send(courses);
});
app.post('/api/course', (req,res) => {
const course = {
id: course.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});
app.get('/api/courses/:id', (req,res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) res.status(404).send('the course with the given ID was not found.');
res.send(course);
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));`
Trying to add another JSON object by using this code in postman
`{
"name": "courses"
}
`
And postman terminal is returning this error:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/courses</pre>
</body>
</html>`
How do I fix this?
Postman show 'Cannot POST /api/courses', meanwhile in your code, you define to use GET on 'api/courses'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/courses</pre>
</body>
</html>
So, you can check further about that
// this is only GET
app.get('/api/courses', (req,res) => {
res.send(courses);
});
// this is use /api/course, not /api/courses
app.post('/api/course', (req,res) => {
const course = {
id: course.length + 1,
name: req.body.name
};
courses.push(course);
res.send(course);
});

While testing basic Nodejs CRUD API using postman, it gives error 'Cannot Post'. How to resolve this issue?

I have created a basic Nodejs CRUD and authentication API.
While testing the basic create operation of a new order using Postman, it gives back the status code 404with response body 'Cannot Post'.
Error:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /order/addorder</pre>
</body>
</html>
The API logic seems to be correct for me and the routers too.
module.exports.add_order = auth, async (req, res) => {
try {
const { productName, quantity } = req.body;
if (!productName || !quantity)
return res.status(400).json({ msg: "Not all fields have been entered" });
const existingorder = await Order.findOne({ productName });
if (existingorder)
return res.status(400).json({ msg: "A product with this name already exists" });
const newOrder = await new Order({
productName,
quantity,
userId: auth.user,
timestamp
});
const savedOrder = await newOrder.save();
res.json(savedOrder);
} catch (err) {
res.status(500).json({ error: err.message });
}
}
The auth function is a middleware function which verifies the JWT.
Router:
orderrouter.get('/readorder', ordercontroller.read_order);
orderrouter.post('/addorder', ordercontroller.add_order);
orderrouter.put('/updateorder', ordercontroller.update_order);
orderrouter.delete('/deleteorder', ordercontroller.delete_order);
module.exports = orderrouter;
The error says you are accesing /order/addorder but in your router you only have /addorder.
Make sure your group routes have the /order prefix

How to transmit data to client-side js file from the server?

I want to transmit my data to client-side JS file from the server, but right now the browser displays data on its main screen like when we use innerHTML property:
I have checked bunch of express.js tutorials but seems like there are no way to send (add, technically) data to the client side js file.
This is a diagram what I'm looking for:
[open the webpage] -> [(in server) get data from database] -> [send data to client-side js file] -> // do stuff more in the client-side
Any tips to resolve this problem?
This is my code:
// Makes display the client-side html, temporary disabled.
// app.use(express.static('client'));
// Queries
const QUERIES = {
prev: 'SELECT * FROM en.prevstore',
curr: 'SELECT * FROM en.currstore',
next: 'SELECT * FROM en.nextstore',
samp: 'SELECT * FROM en.sample'
}
// Create connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'en'
});
// Router
app.use('/', (req, res) => {
db.query(QUERIES.samp, (err, results) => {
let ternary = err ? console.error(err) : res.json(results);
})
})
Client-Side HTML (request from the comment)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="quotes">
should be filled as quotes of data from database
</div>
<div class="color">
should be filled as color of data from database
</div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Client-Side JS:
function getWord() {
fetch('http://localhost:4000')
.then(res => res.json())
.then(({data}) => console.log(data))
}
getWord() // I know it won't work but tried for just in case.
When you tried to load localhost:4000 on your browser and it is requesting your / endpoint.
Your server has to return your static files (index.html & ...) on this endpoint.
app.use(express.static('public'));
// public or any static directory containing your index.html, .js, images ...
Then you can move your / endpoint to something more explicit like /quotes
app.use('/quotes', (req, res) => {
db.query(QUERIES.samp, (err, results) => {
if (err) {
console.log('error', err);
res.status(500);
return res.end(); // closing the response /!\ IMPORTANT
}
res.json(results);
})
})
On your client-side you will have something like that:
function getWord() {
fetch('http://localhost:4000/quotes')
.then(res => res.json())
.then(data => console.log(data))
}

get bigquery results from node.js to browser

I'm running a google compute engine with node.js but am testing using codeanywhere. I am able to run a bigquery request on codeanywhere terminal and get results to display on the terminal console.
but when I try to do the same from an html page, I can't quite get the results to return to the user/browser.
the only node modules I have installed on codeanywhere are firebase and googleapis.
I wish to run the bigquery call on the server side because I want to keep the auth information hidden; otherwise would simply run bigquery api from javascript.
my test.js is:
'use strict';
var google = require('XXX/lib/googleapis');
var bigquery = google.bigquery('v2');
var authClient = new google.auth.JWT(
'XXX#XXX.iam.gserviceaccount.com',
'XXX.pem',
null, ['https://www.googleapis.com/auth/bigquery']);
var request = {
projectId: 'XXX',
//all: true,
auth: authClient
};
var list = bigquery.datasets.list(request, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
return result;
}
});
and my html is:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testing Server Call </title>
<script type = "text/javascript" src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type = "text/javascript" >
$(function() {
$.ajax({
type: 'GET',
url: 'test.js'
success: function(data) {
console.log('yay');
console.log(data);
},
error: function(xhr, status, error) {
console.log('Error: ' + error.message);
}
});
});
</script>
</head>
<body>
hi there
</body>
</html>
I've searched and tested for last couple days and have no idea what I am missing. I keep getting errors like: Error: require is not defined and I can't find any tutorials to help me through the steps to get this accomplished. Thank you in advance for any help.
'use strict';
var http = require('http');
var google = require('XXX/lib/googleapis');
var bigquery = google.bigquery('v2');
var authClient = new google.auth.JWT(
'XXX#XXX.iam.gserviceaccount.com',
'XXX.pem',
null, ['https://www.googleapis.com/auth/bigquery']);
var request = {
projectId: 'XXX',
//all: true,
auth: authClient
};
var server = http.createServer(function(req, res){
var list = bigquery.datasets.list(request, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
response.end(result);
}
});
});
server.listen(8080, function(){});
At frontend you have to specify route where you will make request
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testing Server Call </title>
<script type = "text/javascript" src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type = "text/javascript" >
$(function() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/'
success: function(data) {
console.log('yay');
console.log(data);
},
error: function(xhr, status, error) {
console.log('Error: ' + error.message);
}
});
});
</script>
</head>
<body>
hi there
</body>
</html>
After that you have to just run at commandline node test.js
Here you are using test.js as url which is loading js on client side. You cannot use require on client side and so is this error. You should create a route and give it there.

How to build client server app using node js and html?

I have html file called temp.html
I want to display select query result in that html page.
This is my select query.
SELECT cs_name FROM course_master where cs_id = 4
This query will return following result.
[ { cs_name: 'JAVA programming' } ]
I want to display this result in html page.
Basically I want to use the "GET" request and response using node js.
This is my node js file structure.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'eduportal'
});
connection.connect();
connection.query('SELECT cs_name FROM course_master where cs_id = 4', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
This is my HTML file.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
</head>
<body>
<div id="course_name">
Course Name:<input type="text" id="cname">
</div>
</body>
</html>
I want to display course name in text box which I defined in HTML file.
Can anyone help to bind this text box with mysql using node js?
You can achieve this by socket.io. You need to learn more about this to understand following snippet.
In this i have provided a sample code to full fill your requirement.
Might be possible that some tweaks still in this code so you can change those by your understanding.
Let me clarify about following server.js snippet
In this you can put your all queries to get or set in db.
//server.js
var app = require("express")();
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'eduportal'
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
get_cs_name(function(res,cs_name) {
if (res) {
io.emit('get_cs_name', cs_name);
} else {
io.emit('error');
}
});
});
var get_cs_name = function(callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("SELECT cs_name FROM course_master where cs_id = 4", function(err, rows) {
connection.release();
if (!err) {
callback(true,rows[0].cs_name);
}
});
connection.on('error', function(err) {
callback(false,null);
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
Now run "node server.js" command from CLI. Your http request will be handle on 3000 port. please keep this in mind.
//index.html
<html>
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
socket.on('get_cs_name',function(cs_name){
alert(cs_name);
$("#cname").val(cs_name);
});
});
</script>
</head>
<body>
<div id="course_name">
Course Name:<input type="text" id="cname">
</div>
</body>
</html>
Now its time to browse your html file to see your actual result that it is working or not, please hit http://localhost:3000 in browser.
If any error found please ping me back here.
Thanks

Categories