Posting with angular http.post method - xmlhttprquest cannot load the service - json

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.

Related

Passing Data from node js to html

I am connecting to an authentication server which is returning the credentials and calling to my call back method. How do I pass the authenticated values back to the html to render?
Here is my code
function getHomePage()
{
// alert("here in ajax call")
$.ajax({
url: "/calloidcServer",
headers:{
'Access-Control-Allow-Methods':'POST, PUT, OPTIONS, DELETE, GET',
'Access-Control-Allow-Origin':['https://localhost:3000','https://localhost:9031'],
'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Credentials':true,
'Content-Type':'application/json',
},
type: "GET",
success: function (resp) {
console.log(resp)
$('#testoidc').append(resp);
},
error: function (resp, status, error) {
}
});
}
app.get("/calloidcServer",function (req, res, next) {
console.log('-----------------------------');
console.log('/Start login handler');
next();
},
passport.authenticate('oidc',{scope:"openid"})
)
app.get('/callback',(req,res,next) =>{
console.log(" call back from auth server here")
passport.authenticate('oidc',{ successRedirect: '/user',
failureRedirect: '/' })(req, res, next)
}
)
app.get ("/user",(req,res) =>{
res.header("Content-Type",'application/json');
var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
var decoded = jwt_decoder(req.session.tokenSet.access_token);
console.log(id_token_decode)
console.log(decoded);
console.log(path.join(__dirname + '/public/citizenHome.html'))
res.redirect("/citizenHome.html")
//res.send(JSON.stringify({tokenset:req.session.tokenSet,userinfo:req.session.userinfo},null,2));
})
When I redirect to citizenHome.html, I want to send back some data to it to show in the html? I have not used any view engine.
I am not sure if you can pass values to the HTML directly, but you can use any view-engine with Node.js that can help you pass values from the routes and render the page as you want.
You can use EJS, JADE or Pug.

Node.js HTML response body

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)

Using NodeJS Express, how to properly make a GET call to MySQL in ReactJS?

I have a server running up on Tomcat Apache with a MySQL. For my project, I am using ReactJS + Redux, and NodeJS Express. How do I properly make a GET call to the Tomcat Apache?
In my actions.js for Redux:
callGet() {
var data = {
'Content-Type': 'application/json',
'time': 'TESTING'
}
var init = {
method: 'GET',
      mode: 'cors',
header: data,
};
return function(dispatch) {
dispatch({
type: 'CALL_GET'
});
fetch('http://www.localhost:8080/form/post/create/', init)
.then(result=>result.json())
.then(users=>{
console.log(users);
});
}
}
And for my Node.js Express setup:
app.use('/', function (req, res, next) {
res.sendFile(path.resolve('client/index.html'));
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
yet with the Cannot GET / on the page, I am still getting an error:
Failed to load resource: http://localhost:3005/ the server responded with a status of 404 (Not Found)
What could be the issue or what am I missing? Can't seem to spot the error. Thank you for the help.

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

Angular HTTP Post Request, Payload is nested in JSON Object

I am learning Angular and Node and I am trying to figure out how to have my Angular app hit a separate app hosting a rest API.
The request body is displayed as
{ '{"name":"test"}': '' }
and I expect it to be displayed as
{ "name" : "test"}
This is the front-end app that sends the post request.
$http({
method: 'POST',
url: 'http://localhost:8080/api/test',
data: {
"name": 'test'
},
dataType: "json",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
It is hitting the route defined as
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.post('/test', function(req, res) {
var name = req.body.name;
console.log(req.body);
});
I expect the issue to be with the content-type being application/x-www-form-urlencoded but I cannot figure out how to allow cors with application/json.
JSONP can be used for performing CORS requests (more about json/jsonp here What are the differences between JSON and JSONP?), and in AngularJS documentation - jsonp using $http