Angular HTTP Post Request, Payload is nested in JSON Object - json

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

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.

Runkit - No 'Access-Control-Allow-Origin' header is present on the requested resource

var cors = require("cors");
cors({ origin: '*' });
cors({ allowHeaders: 'X-PINGOTHER'});
cors({ methods: 'GET,HEAD,PUT,PATCH,POST,DELETE'});
exports.endpoint = function(request, response) {
let text = '100,000';
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(text);
}
I am running this on Runkit and still get the error when checking on a website, where I want to display this return value:
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
In your example you've loaded the cors module and configured it, but not actually done anything to get it to intercept the HTTP request and send back your CORS headers.
If you're just using a simple Runkit endpoint, you don't need the CORS module at all – just add the headers in your endpoint, where you're already adding the Content-Type header:
exports.endpoint = function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
});
res.end('foo');
};

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.

Json handling in angular $http post to express

I am trying to post json data to express server using angular $http,
$scope.createTravel = function(){
$http({
url: '/api/travels',
method:"POST",
data: $scope.formData
// headers: {'Content-Type': 'application/json'}
})
};
the post is reaching the server in this console log statement
app.post("/api/travels", function(req, res){
console.log(req);
});
without the json data.

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

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.