I am using the below code to post some JSON data to a url and in response I am getting a HTML page.
var request = require('request');
request.post({
url: "URL OF A WEBSITE",
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
This code works fine I am getting a HTML page in the body tag.
I want to load that HTML page in the browser. How should I do that, I know this is a very basic question but I am very new to node.js someone please help me?
Follow the Express "Hello World" example and use your request call in the route handler:
/*jslint node:true, esversion:6*/
"use strict";
const request = require("request"),
express = require("express"),
app = express();
let my_json_obj = {},
URL_OF_WEBSITE = "http://www.google.com";
app.get("/", function (req, res) {
request.post({
url: URL_OF_WEBSITE,
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json: true
}, function (error, response, body) {
if (error) {
console.log(error);
return res.sendStatus(404);
}
console.log(JSON.stringify(response));
console.log(body);
res.send(body);
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
node.js does have its own way to make a server, but for the sake of brevity and ease I just recommend using Express.
Are you using Express js? It would make things a lot easier when working with Node js apps.
Look into Express routing:
https://medium.com/javascript-scene/introduction-to-node-express-90c431f9e6fd
You can create an Express boilerplate in the terminal by using the command:
express yourappname
you can then put your html/css/js files inside the express-app -> 'public' folder that you just generated.
After that you create routes inside your app.js by doing something like:
// exampledomain.com/
// Loading the file index.html when user navigates to '/'
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// or
// exampledomain.com/getFileURL
// POST request (from your ajax) to '/getFileURL'
// which will then load the about.html file into the browser
app.post('/getFileURL', function(req, res){
// Do more JSON/data handling & Node js stuff here then
// send something back
res.sendFile(path.join(__dirname + '/public/about.html'));
});
There're many more useful functions with Express js, but I think Routing is what you need right now.
p.s. Very useful tools to look into when working with Node js:
Postman (Testing ajax/express/Nodejs routes and responses)
Nodemon (Starting Nodejs server automatically on save)
Related
i am trying to implement a work flow, where, when the user logs in, the user credentials is posted to one of the routes in express via ajax to check if the user exists, if the user exists, the express route will send back a message "authorised" to the ajax call, and the success callback is invoked where another ajax call sends a header along with data to the express route(/reroute). This express /reroute api is trying to res.redirect to another route /homepage. Inside the /homepage route i am attempting to display a html file using res.sendfile, and the res.sendfile is not working.
my login ajax call
$(document).on("click", "#login", (e) => {
const email = $('#logemail').val().trim();
const pass = $('#password').val().trim();
$.ajax({
url: "http://localhost:4000/checkuserexists",
type: "POST",
dataType: "JSON",
data: {
email: email,
pass: pass
},
success: function(data, textStatus, request) {
console.log(data)
if (data.message === "authorised") {
const token = request.getResponseHeader('access-token');
localStorage.setItem("access-token", token);
$.ajax({
url: "http://localhost:4000/reroute",
type: "GET",
dataType: "JSON",
beforeSend: function(xhr) {
xhr.setRequestHeader('access-token', token);
},
data: {
redirectTo: 'homepage'
},
success: function(data) {
console.log(data + " from ajax ")
}
})
} else {
$('.alertbox').show();
$('.alertbox').text("User unauthorised");
}
}
})
})
my express route (/reroute)
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
if (req.header('access-token')) {
const token = req.header('access-token');
const redirectTo = req.query.redirectTo;
if (redirectTo === 'homepage') {
res.setHeader('access-token', token)
res.redirect('/homepage')
}
}
})
module.exports = router;
my homepage route
const express = require('express');
const path = require('path');
const token_middleware = require('../middlewares/jwtauth');
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")))
router.get('/', token_middleware, (req, res) => {
if (req.status === "exists") {
res.sendFile(path.join(__dirname, "../public/homepage.html"));
} else {
res.redirect('/');
}
})
module.exports = router;
You're requesting the URL with Ajax.
The browser asks for /reroute and gets a redirect to /homepage.
It then asks for /homepage and gets an HTML document.
It passes that HTML document to the JavaScript engine and jQuery tries to parse it as JSON (it ignores the Content-Type because you said dataType: "JSON") and errors.
If you want to do this with Ajax, then don't redirect. Return some JSON that tells your code the login was successful. Then you can navigate with client-side JS and the location object.
If you want to redirect, then use a regular form submission and not Ajax.
I'm trying to retrieve data from a SQL database and display that said data on a Reactjs web app. However, all the calls I make to the database results in the HTML of the webpage in focus. I have set the headers, and I've tried to change the way the response from the express call is being handled.
Here is the expressjs script I am using right now:
const express = require('express');
const sql = require('mssql/msnodesqlv8');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const db = require('./db.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
app.use(cors());
app.get('/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
From there, my axios calls look like this:
componentWillMount(){
let self = this;
axios.get("/getTable")
.then(function (response){
console.log(response.data);
self.setState({
data: response.data,
});
})
.catch(function (error){
console.log(error);
})
}
I added the console.log to check what was being returned, and as said, it was the HTML code of the current page of focus.
I made some changes to reflect what steps I took to get the 500 issue out. The current code, however, results in a 404.
If you move your get on top of your put it should work. The problem seems to be that the static clause resolves your request before it gets to your endpoint, so if you do this:
app.get('/counselling/triageadmin/getTable', function (req, res, next){
var request = new sql.Request(db);
request.query('select * from Counselling order by TicketID desc', (err, result) =>{
if (err) { return next(err); }
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(result["recordset"]));
});
});
app.use('/counselling/triageadmin/', express.static(path.join(__dirname, '/build')));
the path to the get will attempt to be matched before you're routed to your static files.
Ideally you would want to have your rest endpoints under a different namespace, i.e. /api but if you decide to keep your setup, this should help.
I think your routes might be conflicting with each other. From the express documentation at: http://expressjs.com/en/4x/api.html#app.use
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
});
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Welcome');
});
Thus, your route '/counselling/triageadmin/getTable' will never be reached, because your route '/counselling/triageadmin/' is intercepting it, responding with static resources.
To solve this, try organizing your routes in a way that puts all of your API requests at a different subfolder, like '/api'. So your getTable endpoint would be located at: '/api/counselling/triageadmin/getTable/' or something like that.
I'm also learning the MEAN stack and I stumbled upon your question since I had the opposite problem. I wanted it to respond with an HTML instead of a JSON
this line of code MAKES it respond with an HTML
res.send(JSON.stringify(result["recordset"]));
(I tried res.send("<h3 HTML T_T </h3>");) and it did send and HTML
however, if you try
res.json(String(req.params.id)); <= Notice the res.json instead of res.send
It responds with a JSON :)
I hope this helped
So lets say I have a file called string.js, it might look something like this:
var hello = "Hello World!";
And lets say I have a file called hello.html.
How do I now view that string upon opening hello.html in my browser?
Your task can be divided into two parts:
1.add javascript codes to html and control then content
2.use node.js server to serve the html file up
The first task is pretty straightforward. You just have to include the .js file in your html. This is basic html-javascript application. You can find a lot of resource to learn it. W3schools is a very good site for beginners.
You have several ways to do task 2. Your objective is serve static contents. Let's use Hapi framework as an example.
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/sample',
handler: function (request, reply) {
reply.file('/your html file');
}
});
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
Now, once you enter localhost:3000/sample in your browser, you will be able to see the result.
In the code, what you did is creating a Hapi server and setting a route. The route replies you a html file once it is called.
Node.js runs server side. To be able to display Hello world, you would need to do something like:
const http = require('http');
http.createServer((req, res) => {
res.end('Hello World');
}).listen(3000);
I have a server as following:
app.post('/', function(req, res, next) {
console.log(req);
res.json({ message: 'pppppppppppppssssssssssssss ' });
});
The request is sent from a client as:
$.ajax({
type: "POST",
url: self.serverURI,
data: JSON.stringify({ "a": "128", "b": "7" }),
dataType: 'json',
success: function (result) {
console.log(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
so far the connection fine.
My problem is in the server:
console.log(req);
where I want to read the data I sent. How can I read { "a": "128", "b": "7" } from req?
Although you're not mentioning it, your code looks like it's written for an Express environment. My answer is targeted to this.
Make sure to use body-parser for Express. In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script. If not:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Installation with npm: npm install body-parser --save
The parsed JSON can then be accessed through req.body:
app.post('/', function(req, res, next) {
console.log(req.body); // not a string, but your parsed JSON data
console.log(req.body.a); // etc.
// ...
});
For Express 4+,
const express = require("express");
const app = express();
app.use(express.json());
Then, you can use req.body as expected.
app.post("/api", (req, res) => {
/*
If the post request included { data: "foo" },
then you would access `data` like so:
*/
req.body.data
...
});
Angular $http.post method is not posting JSON to service (RESTFul service, node service).
Showing the following error :
XMLHttpRequest cannot load /some/service. Invalid HTTP status code 404
Here is the posted code
$http({method:'POST', url:'/some/service/',data:{"key1":"val1","key2":"val2"}}).success(function(result){
alert(result);
});
The same code is working with the old version of my chrome i.e, v29...* . I updated my chrome to V30...* . Now, it is not working. Not working in the Firefox as well. Is there any problem with chrome and Firefox?
Can anybody help?
I came across a similar issue after updating Chrome to version 30.0.1599.101 and it turned out to be a server problem.
My server is implemented using Express (http://expressjs.com/) and the code below allowing CORS (How to allow CORS?) works well:
var express = require("express");
var server = express();
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
next();
}
server.configure(function () {
server.use(allowCrossDomain);
});
server.options('/*', function(req, res){
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with');
res.send(200);
});
server.post('/some_service', function (req, res) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
// stuff here
//example of a json response
res.contentType('json');
res.send(JSON.stringify({OK: true}));
});
The HTTP request looks like:
$http({
method: 'POST',
url: 'http://localhost/some_service',
data: JSON.stringify({
key1: "val1",
key2: "val2"
}),
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(
function (data, status, headers, config) {
//do something
}
).error(
function (data, status, headers, config) {
//do something
}
);
As pointed out in here (https://stackoverflow.com/a/8572637/772020), the idea is to ensure that your server handles properly the OPTIONS request in order to enable CORS.
Well, a new chrome update was released a couple of days ago. Check the patch notes from that release if they changed anything security related.
My extension stopped working both in FF and Chrome a couple of days ago.