angular - make it to call api that accept json format - json

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.

Related

Express Send data via request body but request methode is GET?

Hey there It's my first post so sorry if I am doing something wrong here but be patient with me ;)
I am trying to send some data in JSON format to my MySQL DB using Express but whenever I use something else besides app.get() it fails. I guess it is because the request methode shown in the browser is always GET but I dont know why.
What am I doing wrong? How can the request method be GET when I am using app.post()?
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'masterkey',
database: 'articelStorage'
});
const app = express();
app.use(bodyParser.json());
app.use(express.json());
//connect to db
db.connect((err) => {
if (err) {
throw err;
}
console.log('Myql connected...');
});
app.listen('3000', () => {
console.log('Server started and running on port 3000...');
});
app.get('/getOne/:code', (req, res) => {
let sql = "SELECT * FROM articels WHERE acode ='" +req.params.code+"'";
db.query(sql, (err, result) => {
if (err) throw err;
res.send(result);
});
});
app.delete('/deleteOne/:code', (req, res) => {
let sql = "DELETE FROM articels WHERE acode ='" +req.params.code+ "'";
db.query(sql, (err, result) => {
if (err) throw err;
res.send(result);
});
});
Here is the result I get:
Cannot GET /deleteOne/DE12345678
And the Headers:
General:
Request URL: http://localhost:3000/deleteOne/DE12345678
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Connection: keep-alive
Content-Length: 159
Content-Security-Policy: default-src 'self'
Content-Type: text/html; charset=utf-8
Date: Thu, 07 Mar 2019 13:12:36 GMT
X-Content-Type-Options: nosniff
X-Powered-By: Express
Request Headers:
Accept: text/html,application/xhtml+xml,application/xml;
q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Host: localhost:3000
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36
Thx in advance.
I think there is a misconception here.
When you are declaring app.get('/getOne/:code', (req, res)=>{..}) it means the route is accessible by HTTP GET. Similarly for app.delete the route is accessible by request method HTTP DELETE.
Now, when you open a url in browser it is ALWAYS a HTTP GET request. That's why the /getOne will work, but not the delete one.
You need to use Postman(or curl) like application to test your REST api.
If you are accessing an endpoint from Client, use axios or request or xmlhttprequest and set the request method what you want it to be.
For example,
axios({url:url, method:'delete', { data: { foo: "bar" } });// or axios.delete(..)

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');
};

Emberjs Data Models to 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);
}
});
});
}
}
});

Restangular won't change Http Content-Type

In order to send a file as part of my form, I changed the content type to "multipart/form-data", but when I check the console, it's still using application/json;charset=utf-8 And Node.js (with Sails.js framework) prints an error saying it's invalid JSON.
Here is the code:
$rootScope.objects.user.withHttpConfig({
transformRequest: angular.identity
}).customPUT($scope.objects.user, "", { // user object contains a file
'Content-Type': "multipart/form-data" // should change content-type. I've tried using `undefined` as well
}).then(function(resp) {
if (resp == "OK") {
$scope.successes = [{
msg: "Saved"
}];
}
}, function(err) {
console.log(err);
$scope.errors = err.data.errors;
});
The "Inspect Network Request" tab in Google Chrome reads:
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0
Referer: http://localhost:1337/user/settings
Host: localhost:1337
DNT: 1
Content-Type: application/json;charset=utf-8
Content-Length: 505679
Connection: keep-alive
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Accept: application/json, text/plain, */*
As said in comment above and According to docs you should pass headers as fourth parameter. So your code should be
$rootScope.objects.user.withHttpConfig({
transformRequest: angular.identity
}).customPUT(
$scope.objects.user,
undefined,
undefined,
{
'Content-Type': "multipart/form-data"
}
).then(function(resp) {
if (resp == "OK") {
$scope.successes = [{
msg: "Saved"
}];
}
}, function(err) {
console.log(err);
$scope.errors = err.data.errors;
});
Reference url : https://github.com/mgonto/restangular#custom-methods

Google Docs script to fetch some web information

I am trying to connect to a table score that exits in a flash game.
When using the browser the header that i am sending it's this one
POST /game/json?h=c1234567890f HTTP/1.1
Host: pt3.forgeofempires.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: sid=awsndax7nsow; req_page_info=game_v1; start_page_type=game; start_page_version=v1
Connection: keep-alive
Referer: http://cdn.pt.forgeofempires.com/swf/Main.swf?123456789
Content-type: application/x-www-form-urlencoded
Content-length: 161
34c4ceb6d8[{"requestClass":"ClanService","requestMethod":"getOwnClanData","requestData":[],"requestId":1,"__class__":"ServerRequest","clientVersionNumber":0.31}]
After looking for a while (my acknowledgement in JavaScript is not that height), i did find some examples and after understanding them i did make my own code.
function test(){
var header =
{
'Host': 'pt3.forgeofempires.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Cookie': 'sid=awsndax7nsow; req_page_info=game_v1; start_page_type=game; start_page_version=v1',
'Connection': 'keep-alive',
'Referer': 'http://cdn.pt.forgeofempires.com/swf/Main.swf?123456789',
'Content-type': 'application/x-www-form-urlencoded',
'Content-length': '161',
'': '96c4ceb6d9[{"requestClass":"ClanService","requestMethod":"getOwnClanData","requestData":[],"requestId":4,"__class__":"ServerRequest","clientVersionNumber":0.31}]'
}
var url = "http://pt3.forgeofempires.com/game/json?h=c1234567890f";
var h = {
'method' : "post",
'payload' : header
};
var response = UrlFetchApp.fetch(url, h);
return response;
}
When i run the code it goes always to the login page.
Not sure if this is happening because of any script error or simple because it's a different ip address accessing to my account.
No sure as well how to send the last part, because the last part it's a text data only.
Any help will be appreciated... thanks in advance
You are adding your headers as a payload. UrlFetchApp provides a way to add headers. Use that
var h = {
'method' : "post",
'headers' : header
};
var response = UrlFetchApp.fetch(url, h);
I'm not sure what your payload is. In the list of headers, there is a blank header - is this the payload ? If yes, then you have to add the payload separately.
var h = {
'method' : "post",
'headers' : header,
'payload' : '96c4ceb6d9[{"requestClass":"ClanService","requestMethod":"getOwnClanData","requestData":[],"requestId":4,"__class__":"ServerRequest","clientVersionNumber":0.31}]'
};
var response = UrlFetchApp.fetch(url, h);
Note: Ensure that you remove the blank header from the list of headers.