Emberjs Data Models to JSON - json

I have the following route:
Loads.TestRoute = Ember.Route.extend({
model: function() {
return this.store.find('load');
}
});
This to the best of my knowledge will return all instances of load in the data store, which in this case can be anywhere from 1 to 100. For this application, I am using a local storage adapter.
My controller looks like this:
Loads.TestController = Ember.ArrayController.extend({
actions: {
test: function () {
var loads = this.get('model');
var driverId = getCookie("id");
this.store.find("driver", driverId).then(function (driver,loads) {
$.ajax({
type: "POST",
data: JSON.stringify({ Driver: driver, Loads: loads }),
url: "api/build",
contentType: "application/json",
success: function (message) {
alert(message);
}
});
});
}
}
});
What I'm trying to accomplish is to send all instances of the model 'load' along with a specific instance of the model driver as a JSON object to an API on my server that builds spreadsheets.
When I run this, I can see in the request payload that the Driver model object is turned into JSON, but the Loads are not. Here is what is in the payload:
Remote Address:[::1]:49438
Request URL:http://localhost:49438/api/build
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:66
Content-Type:application/json
Cookie:id=atcn4
Host:localhost:49438
Origin:http://localhost:49438
Referer:http://localhost:49438/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payloadview source
{Driver: {firstName: "Ron", lastName: "Burgandy", truck: "12"}}
How can I update this to make it so both the driver and loads models are sent in the Payload?
Thanks for any help in advance!

You need to make sure both promises from your store are resolved before you send off your ajax request. Use Ember.RSVP.hash
Loads.TestController = Ember.ArrayController.extend({
actions: {
test: function () {
var driverId = getCookie("id");
Ember.RSVP.hash({
loads: this.store.find('load'),
driver: this.store.find('driver', driverId)
}).then(function(data) {
$.ajax({
type: "POST",
data: JSON.stringify({ Driver: data.driver, Loads: data.loads }),
url: "api/build",
contentType: "application/json",
success: function (message) {
alert(message);
}
});
});
}
}
});

Related

body-parser substitution app.use(express.json({ limit: "1mb" })); leads to 500 Internal Server error

I use body-parser version 1.19.0 in my NodeJS project together with express version 4.17.1 like this:
import {
Router
} from "express";
import bodyParser from "body-parser";
const jsonParser = bodyParser.json({
limit: "1mb",
});
const apiRoutes: Router = Router();
apiRoutes.post(
"/:id",
accessFilter,
localDFilter,
jsonParser,
fetchProductData,
);
As the bodyParser.json() is marked as deprecated, I would like to get rid off it.
So I have done:
const app = express();
app.use(express.json({
limit: "1mb"
}));
Unfortunately I always get a 500 Internal Server Error for some requests that work perfectly with the deprecated bodyParser.json().
So I have added this in my frontend for axios:
const response = yield call(ApiFetcher.request, {
method: "GET",
headers: {
Accept: "application/json",
},
url: getLoadOptionsURI(API_OPTIONS_ENDPOINT, uriParams),
params: {
...getQueryParams(),
mandant,
},
});
What is the problem with my express.json(..) approach ?
Replace:
headers: {
Accept: "application/json",
},
with:
headers: {
Content-Type: "application/json",
},
Accept header is for the client. it specifies the media type the client expects from the server's response. Content-type specifies the media type sent in the request from the client to the server.
Also, just to clarify, some of the comments mentioned that the request might be exceeding the limit. If that was the case the response would be 413 Payload Too Large

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

Node.js scraping with the request module

I want to get html from a web. But it show like that.
meta http-equiv=refresh content="0;url=http://www.skku.edu/errSkkuPage.jsp">
But when I use https://www.naver.com/ instead of https://www.skku.edu/skku/index.do, it works well.
I want to know the reason.
Here's my code.
var request = require('request');
const url = "https://www.skku.edu/skku/index.do";
request(url, function(error, response, body){
if (error) throw error;
console.log(body);
});
The website blocks the request that is coming from programmatic script checking User-Agent in the request header.
Pass the user-Agent that web-browser(eg: Google chrome) sends and it should work.
var request = require('request');
var options = {
'method': 'GET',
'url': 'https://www.skku.edu/skku/index.do',
'headers': {
'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
I wouldn't recommend request module as it is not maintained for changes anymore. see it here - https://github.com/request/request/issues/3142
You could look for alternatives in form of got, axios etc which makes code much more readable and clear. And most important thing - Native support for promises and async/await The above code will look like
var got = require('got');
const url = "https://www.skku.edu/skku/index.do";
(async () => {
const response = await got(url);
console.log(response.body);
})();

Connecting to HTTPS web services API with node.js v4.2.6?

I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}

angular - make it to call api that accept json format

I am very new to angularjs.
I am trying to make the http call and posting object to the api which only accept json.
'use strict';
// Declare app level module which depends on views, and components
var app = angular.module('ngShow', ['ngRoute','ngResource']);
app.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html' });
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.
config(['$httpProvider', function($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Access-Control-Max-Age'] = '1728000';
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
$httpProvider.defaults.useXDomain = true;
}]);
but seems doesn't work from the request headers.
Request Headers 15:31:10.000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0
Pragma: no-cache
Origin: http://localhost:63342
Host: localhost:8080
DNT: 1
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-max-age
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
UPDATE #001
Added my loginService.js - it is calling the api ok but just not the json.
app.factory('loginService', function($http){
return{
login:function(user){
console.log("enter login service");
var $promise=$http.post('http://localhost:8080/api/login',user); //send data to the api
$promise.then(function(msg){
if(msg.data=='succes') console.log('succes login');
else console.log('error login');
});
}
}
});
I've got following concerns here:
You use 2 config sections for one module. Not sure if this approach is expected.
Accordingly the documentation, such params are set in run section
Assuming that the user param in the login() method of your loginService factory is the object you want to send as your JSON payload, you can try the following:
var payload = JSON.stringify(user);
var promise = $http({
url: '/api/login',
method: 'POST',
data: payload,
headers: {'Content-Type': 'application/json'}
});
promise.then(function(...) {
...
});
UPDATE:
I would also consolidate the two .config() calls in your code.
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html' });
$routeProvider.otherwise({redirectTo: '/login'});
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Access-Control-Max-Age'] = '1728000';
$httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';
$httpProvider.defaults.useXDomain = true;
}]);
You're already setting the Content-Type header globally (i.e. for all requests) using $httpProvider.defaults.headers.common['Content-Type'], so the headers: {'Content-Type': 'application/json'} in my code above is redundant.