I am trying to build an application with Asp.net web api and Angularjs
I am trying to get data from API but I am getting a null error as a result.
Asp.net web api code
[RoutePrefix("api/user")]
public class UserController : ApiController
{
[Route("login")]
[HttpGet]
public HttpResponseMessage login(string userId, string password)
{
...code to fetch data
return Request.CreateResponse(HttpStatusCode.OK, result);
}
web config
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
Angular Js Code
this.get = function (url, headers = {}) {
/// creating a defer
var def = $q.defer();
$http({
url: url,
dataType: 'json',
method: 'GET',
data: '',
headers: headers
}).success(function (data) {
def.resolve(data);
}).error(function (error) {
def.reject(error);
});
return def.promise;
};
Result
When I am trying to get the result by hitting the API URl I am getting error null
If I am opening the url in web browser then it is returning the JSON
Network Log
{
"log": {
"version": "1.2",
"creator": {
"name": "WebInspector",
"version": "537.36"
},
"pages": [],
"entries": [
{
"startedDateTime": "2016-06-02T16:27:59.550Z",
"time": 25.981999933719635,
"request": {
"method": "GET",
"url": "http://localhost:62158/api/user/login?userId=undefined&password=abc",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Origin",
"value": "http://localhost:8000"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate, sdch"
},
{
"name": "Host",
"value": "localhost:62158"
},
{
"name": "Accept-Language",
"value": "en-US,en;q=0.8,hi;q=0.6,und;q=0.4"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"
},
{
"name": "Accept",
"value": "application/json, text/plain, */*"
},
{
"name": "Referer",
"value": "http://localhost:8000/"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [
{
"name": "userId",
"value": "undefined"
},
{
"name": "password",
"value": "abc"
}
],
"cookies": [],
"headersSize": 429,
"bodySize": 0
},
"response": {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Pragma",
"value": "no-cache"
},
{
"name": "Date",
"value": "Thu, 02 Jun 2016 16:27:59 GMT"
},
{
"name": "Server",
"value": "Microsoft-IIS/8.0"
},
{
"name": "X-AspNet-Version",
"value": "4.0.30319"
},
{
"name": "X-Powered-By",
"value": "ASP.NET"
},
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
{
"name": "Cache-Control",
"value": "no-cache"
},
{
"name": "X-SourceFiles",
"value": "=?UTF-8?B?QzpcVXNlcnNca2lyXERlc2t0b3BcRSBEcml2ZVxXb3JrIExpdmVcTml0aW4gS0sgU29mdHdhcmVcVmlkZW9MaWJyYXJ5XHByb2plY3RcVmlkZW9MSWJyYXJ5XFZpZGVvTElicmFyeVxhcGlcdXNlclxsb2dpbg==?="
},
{
"name": "Content-Length",
"value": "46"
},
{
"name": "Expires",
"value": "-1"
}
],
"cookies": [],
"content": {
"size": 0,
"mimeType": "application/json",
"compression": 447,
"text": ""
},
"redirectURL": "",
"headersSize": 447,
"bodySize": -447,
"_transferSize": 0,
"_error": ""
},
"cache": {},
"timings": {
"blocked": 2.24999990314245,
"dns": -1,
"connect": -1,
"send": 0.19500008784235012,
"wait": 22.8659999556839,
"receive": 0.6709999870509336,
"ssl": -1
},
"serverIPAddress": "[::1]",
"connection": "15008"
}
]
}
}
Same Hit in browser giving result
As KKKKKKKK and rick have already pointed out you don't need to create another promise as $http.get will already return one. You should also make use of then as opposed to succcess/failure
So what you want should look like this:
function getData() {
return $http.get('path-to-api/api.json').then(
function success(result) {
// Do stuff with it
return result.data;
},
function failure(err) {
return err;
});
}
Note this places the call in a service and returns the function in an object from that service.
EDIT
Because the comments concates URLS I'll add this as an edit:
So the url you're hitting on the angular side is:
http://localhost:62158/api/user/login?userId=undefined&password=abc.json
or is http://localhost:62158/api/user/login?userId=undefined&password=abc
#Katana24 I do not know how to thank you but you made me get this answer... thanks a lot.
Reason
Asp.net web api does not allow cross origin request until and unless you add Access-Control-Allow-Origin in web.config file. I made it * so from any origin the APIes is accessible.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
Related
’m trying to parse the response data to view property data. However, I searched through all the properties in the response data but none seemed to hold property data.
For anybody who isn’t familiar with realtor API this is the site I’m talking about. The data shows the exact way I want to receive mine
https://rapidapi.com/apidojo/api/realtor/endpoints
fetch("https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0", {
"method": "GET",
"headers": {
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac"
}
})
.then(response => {
console.log(response.json());
})
.catch(err => {
console.log(err);
});
I was able to use Postman and test this endpoint and found that you likely need to be looking for the properties array and loop through the objects and sub-arrays/objects contained in each parent object of the properties array to get to the details about each property.
Inside of this array are objects that contain the address, latitude, longitude, etc.
I would recommend using Postman if you are not already, doing a GET request when doing so and using the same headers. You should see the same. Using Postman is a great way to test endpoints!
Here is an example of the data that is returned from the results inside of the properties array when hitting your endpoint with a GET request:
"properties": [
...
...
{
"property_id": "R3188507190",
"listing_id": "612930061",
"prop_type": "apartment",
"list_date": "2018-08-20T17:22:00.000Z",
"last_update": "2020-08-25T08:17:00.000Z",
"year_built": 2018,
"listing_status": "active",
"beds": 0,
"prop_status": "for_rent",
"address": {
"city": "Arverne",
"country": "USA",
"county": "Queens",
"lat": 40.589922,
"line": "190 Beach 69th St",
"postal_code": "11692",
"state_code": "NY",
"state": "New York",
"time_zone": "America/New_York",
"neighborhood_name": "Rockaway Peninsula",
"neighborhoods": [
{
"id": "8c06e34c-3044-5621-aea4-b59d9ddde719",
"level": "macro_neighborhood",
"name": "Rockaway Peninsula"
}
],
"lon": -73.79765
},
"client_display_flags": {
"presentation_status": "for_rent",
"is_showcase": true,
"lead_form_phone_required": true,
"price_change": 0,
"has_specials": false,
"is_mls_rental": false,
"is_rental_community": true,
"is_rental_unit": false,
"is_co_star": true,
"is_apartmentlist": false,
"suppress_map_pin": false,
"suppress_phone_call_lead_event": true,
"price_reduced": false,
"allows_cats": true,
"allows_dogs": true,
"allows_dogs_small": true,
"allows_dogs_large": true
},
"agents": [
{
"primary": true
}
],
"lead_forms": {
"form": {
"name": {
"required": true,
"minimum_character_count": 1
},
"email": {
"required": true,
"minimum_character_count": 5
},
"move_in_date": {
"required": true,
"default_date": "2020-09-01T12:00:00Z",
"minimum_days_from_today": 1,
"maximum_days_from_today": 180
},
"phone": {
"required": true,
"minimum_character_count": 10,
"maximum_character_count": 11
},
"message": {
"required": false,
"minimum_character_count": 0
},
"show": false
},
"show_agent": false,
"show_broker": false,
"show_provider": false,
"show_management": false
},
"lot_size": {
"size": 0,
"units": "sqft"
},
"building_size": {
"units": "sqft"
},
"rdc_web_url": "https://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"rdc_app_url": "move-rdc://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"community": {
"baths_max": 1,
"baths_min": 1,
"beds_max": 1,
"beds_min": 1,
"contact_number": "(844) 454-2289",
"id": 1839240,
"name": "The Tides At Arverne By The Sea",
"price_max": 2195,
"price_min": 2195,
"source_id": "46dfexj",
"sqft_max": 659,
"sqft_min": 659
},
"data_source_name": "co-star",
"source": "community",
"page_no": 1,
"rank": 1,
"list_tracking": "type|property|data|prop_id|3188507190|list_id|612930061|comm_id|1839240|page|rank|data_source|co-star|property_status|product_code|advantage_code^1|1|3K2|E8|0^^$0|1|2|$3|4|5|6|7|8|9|G|A|H|B|C|D|I|E|J|F|K]]",
"photo_count": 19,
"photos": [
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f75218736o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3178227471o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3306091863o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1799178643o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f884518299o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1142482343o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f624998745o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3641852832o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2581754924o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1976580515o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f586291969o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2803556443o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3294921843o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f852583007o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f4164216811o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3902720508o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f850731407o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2027588413o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f805760224o.jpg"
}
]
},
...
...
]
If the response is not returning the data you expect then it could be that the format of your fetch GET request code is not quite right.
EDIT: In fact, that is exactly the problem I do believe. So, it should probably work if you try to structure your fetch similarly to this:
let url = 'https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0';
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'realtor.p.rapidapi.com',
'x-rapidapi-key': 'e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac'
}})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
I'm writing an api that gets a JSON in NODE.JS. The method of sending the data is POST.
To ease the management of requests I'm using lib Express and BodyParser to interpret the body of POST requests.
I'm grouping information into a javascript object like this:
const data = {
"plan": "312409959F9FDDE444959F9C950201D7",
"sender": {
"name": $("[name=pname]").val(),
"email": $("[name=pemail]").val(),
"hash": credentials.hash,
"phone": {
"areaCode": $("[name=pphone]").val().substring(0, 2),
"number": $("[name=pphone]").val().substring(2, 11)
},
"address": {
"street": $("[name=paddress]").val(),
"number": $("[name=pnumber]").val(),
"complement": $("[name=pcomplement]").val(),
"district": $("[name=pbairro]").val(),
"city": $("[name=pcity]").val(),
"state": $("[name=puf]").val(),
"country": "BRA",
"postalCode": $("[name=pcep]").val()
},
"documents": [{
"type": "CPF",
"value": $("[name=pcpf]").val()
}]
},
"paymentMethod": {
"type": "CREDITCARD",
"creditCard": {
"token": credentials.token,
"holder": {
"name": $("[name=pownername]").val(),
"birthDate": $("[name=pbirthday]").val().split('-').reverse().join('/'),
"documents": [{
"type": "CPF",
"value": $("[name=pcpf2]").val()
}],
"phone": {
"areaCode": $("[name=pphone2]").val().substring(0, 2),
"number": $("[name=pphone2]").val().substring(2, 11)
}
},
}
}
}
The request is sent as follows:
$.post('/adherence', data, function (msg) {
console.log(msg)
})
And the receipt on my backend is like this:
app.post('/adherence', (req, res) => {
try {
console.log(req.body);
res.send("OK");
} catch (e) {
console.log(e);
res.send(e);
}
});
But what I get in req.body is this:
{ plan: '312409959F9FDDE444959F9C950201D7',
'sender[name]': 'FRancisco',
'sender[email]': 'falisson.sv#sandbox.pagseguro.com.br',
'sender[hash]': 'ceedf0fd2ffd35f4054104d305088e19e8ca9333bbf70be10bd2ea6f94af226a',
'sender[phone][areaCode]': '63',
'sender[phone][number]': '991047876',
'sender[address][street]': '1105 sul qi 3 al 3 lt 1',
'sender[address][number]': '1',
'sender[address][complement]': '',
'sender[address][district]': 'centro',
'sender[address][city]': 'palmas',
'sender[address][state]': 'TO',
'sender[address][country]': 'BRA',
'sender[address][postalCode]': 'CEP',
'sender[documents][0][type]': 'CPF',
'sender[documents][0][value]': 'CPF',
'paymentMethod[type]': 'CREDITCARD',
'paymentMethod[creditCard][token]': 'b2f303ba63964404b6c466323deb9078',
'paymentMethod[creditCard][holder][name]': 'LUCINEIA',
'paymentMethod[creditCard][holder][birthDate]': '11/01/1990',
'paymentMethod[creditCard][holder][documents][0][type]': 'CPF',
'paymentMethod[creditCard][holder][documents][0][value]': 'CPF',
'paymentMethod[creditCard][holder][phone][areaCode]': '63',
'paymentMethod[creditCard][holder][phone][number]': '991047876' }
In my opinion, everything is normal, and it was for me to be receiving the JSON in the format sent. What's wrong with my code?
Try sending your request like that:
$.ajax({
url: '/adherence',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
console.log(msg)
})
});
I'm trying to return some data from an api, however when I hit the server I receive a bad request message. I think the issue lies with my JSON Stringify, have I used this function correctly to concatenate my request body?
Output:
{ request:
{ passengers: { kind: 'qpxexpress#passengerCounts', adultCount: 1 },
slice: [ [Object] ],
saleCountry: 'GB',
ticketingCountry: 'GB',
solutions: 10 } }
Upload successful! Server responded with: {
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "Invalid inputs: received empty request."
}
],
"code": 400,
"message": "Invalid inputs: received empty request."
}
}
Code:
var express = require('express')
var router = express.Router()
var request = require('request')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' })
})
let flightRequest = {
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}}],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
console.log(JSON.stringify("hello" + flightRequest))
JSON.stringify(flightRequest)
console.log(flightRequest)
request.post({url:'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX', flightRequest: flightRequest}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
module.exports = router
I think you need to post the request as follows
request({
url: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX',
method: "POST",
json: JSON.stringify(flightRequest)
}, function optionalCallback(err, httpResponse, body) { ...
or it could be
request.post({
url: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX',
json: JSON.stringify(flightRequest)
}, ...
have I used this function correctly to concatenate my request body?
This Code
let flightRequest =
{
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [
{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}
}
],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
let flightAppend = {"appended text":"hello"}
var obj = Object.assign(flightAppend, flightRequest)
console.log(JSON.stringify(obj))
Produces This Output
{
"appended text": "hello",
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [
{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}
}
],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
I don't know if that's what you're looking for, or which side of the API you're on, but the output is valid JSON
As opposed to the original code which produces "hello[object Object]"
I am trying to create Recurring event using Outlook Rest API in node.js for that I gone through documents whcihis provided by Microsoft but there is no sample example found ,but I am getting error as
{
"error": {
"code": "RequestBodyRead",
"message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartObject' node was expected."
}
}
My Code:
var jsonBody = {
"Subject": "test event",
"Body": {
"ContentType": "HTML",
"Content": "sadsad"
},
"Start": "2016-05-27T00:00:00.000Z",
"End": "2016-05-27T00:30:00.000Z",
"Attendees": result,
"Type":"Occurrence",
"Recurrence": {
"Pattern": {
"DayOfMonth": 0,
"Month": 0,
"Type": "Daily",
"Interval": 3,
"FirstDayOfWeek": "Sunday"
},
"Range": {
"StartDate": "2015-05-27T00:00:00Z",
"EndDate": "0001-01-01T00:00:00Z",
"NumberOfOccurrences": 0,
"Type": "NoEnd"
}
}
};
var optionsForCreatingcalendar = {
uri: 'https://outlook.office.com/api/v2.0/me/events',
port: 443,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
json: true,
body: jsonBody,
resolveWithFullResponse: true,
simple: false
};
// --- API call using promise-----
rp(optionsForCreatingcalendar)
.then(function(response) {
},function(err){
});
Can some one help me resolve it?
Thanks in Adavnce.
Thank god,I solved my problem.Because of Date format I was not able to create Event.
Working Code:
var jsonBody = {
"Subject": "test event",
"Body": {
"ContentType": "HTML",
"Content": "sadsad"
},
"Start": {
"DateTime": "2016-05-21T10:10:00",
"TimeZone":"India Standard Time"
},
"End": {
"DateTime":"2016-05-21T11:10:00",
"TimeZone":"India Standard Time"
},
"Attendees": result,
"Type":"Occurrence",
"Recurrence": {
"Pattern": {
"DayOfMonth": 0,
"Month": 0,
"Type": "Daily",
"Interval": 3,
"FirstDayOfWeek": "Sunday"
},
"Range": {
"StartDate": "2016-05-27",
"EndDate": "2016-06-27",
"NumberOfOccurrences": 0,
"Type": "NoEnd"
}
}
};
Thank you All.
I am having a problem getting the POST data from a Facebook action. When you submit a comment on FB it posts to this url: https://www.facebook.com/ufi/add/comment/?__pc=EXP1%3ADEFAULT
In the request, the post data for the post exists:
Here is an example of the actual comment from the post data:
comment_text:test this is a test
When I try to access this through a Chrome Extension I can't seem to get this data. I've tried parsing the requestBody, but it is empty. I then tried to see if any of the other requestmethods would work, and I can't seem to find the data anywhere.
manifest.json:
{
"background": {
"scripts": [ "background.js" ]
},
"manifest_version": 2,
"name": "Interaction Tracker",
"description": "Track social interactions by social site and customizable categories.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [ "webRequest", "webRequestBlocking", "webNavigation", "tabs", "<all_urls>", "debugger" ]
}
background.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["blocking", "requestBody"]
);
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]
);
chrome.webRequest.onSendHeaders.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["requestHeaders"]
);
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
chrome.webRequest.onAuthRequired.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
chrome.webRequest.onResponseStarted.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["responseHeaders"]
);
chrome.webRequest.onBeforeRedirect.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["responseHeaders"]
);
chrome.webRequest.onCompleted.addListener(
function(details) {
if (details.method == "POST") {
var fb_add_comment_regex = new RegExp(".*facebook\.com\/ufi\/add\/comment.*");
if ( fb_add_comment_regex.test(details.url) ) {
console.log(JSON.stringify(details));
}
}
},
{urls: ["<all_urls>"]},
["responseHeaders"]
);
Below is the output from the console.log statements for each type of request:
onBeforeRequest
{
"frameId": 0,
"method": "POST",
"parentFrameId": -1,
"requestBody": {
"raw": [
{
"bytes": {
}
}
]
},
"requestId": "6724",
"tabId": 93,
"timeStamp": 1444749653166.1,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
onBeforeSendHeaders
{
"frameId": 0,
"method": "POST",
"parentFrameId": -1,
"requestHeaders": [
{
"name": "Origin",
"value": "https:\/\/www.facebook.com"
},
{
"name": "X-DevTools-Emulate-Network-Conditions-Client-Id",
"value": "AB63796C-002A-4670-8A56-547F8D13CA8C"
},
{
"name": "User-Agent",
"value": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/45.0.2454.101 Safari\/537.36"
},
{
"name": "Content-Type",
"value": "application\/x-www-form-urlencoded"
},
{
"name": "Accept",
"value": "*\/*"
},
{
"name": "Referer",
"value": "https:\/\/www.facebook.com\/GrauZug?ref=br_rs"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate"
},
{
"name": "Accept-Language",
"value": "en-US,en;q=0.8"
},
{
"name": "Cookie",
"value": "datr=pvA2VDnTeMjGlWhVYRrnhBtO; lu=gh2TS-IuZkO-Ku-YhAzkiFIw; p=-2; c_user=100000720140344; fr=07LqqXcCamvBIa9Ww.AWU6e_qoHRglPj51gS-CF6uF-r8.BVY1Qk.DT.FYB.0.AWVvgvJA; xs=79%3A403i2b7V6bYSIA%3A2%3A1439311770%3A8344; csm=2; s=Aa4bsJIf94u-JaGr.BVyieb; presence=EDvF3EtimeF1444749507EuserFA21B00720140344A2EstateFDsb2F1444656454966Et2F_5b_5dElm2FnullEuct2F1444743344BEtrFnullEtwF2707054892EatF1444748467285G444749507665CEchFDp_5f1B00720140344F101CC; act=1444749649564%2F26"
}
],
"requestId": "6724",
"tabId": 93,
"timeStamp": 1444749653173.2,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
onSendHeaders
{
"frameId": 0,
"method": "POST",
"parentFrameId": -1,
"requestHeaders": [
{
"name": "Origin",
"value": "https:\/\/www.facebook.com"
},
{
"name": "X-DevTools-Emulate-Network-Conditions-Client-Id",
"value": "AB63796C-002A-4670-8A56-547F8D13CA8C"
},
{
"name": "User-Agent",
"value": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/45.0.2454.101 Safari\/537.36"
},
{
"name": "Content-Type",
"value": "application\/x-www-form-urlencoded"
},
{
"name": "Accept",
"value": "*\/*"
},
{
"name": "Referer",
"value": "https:\/\/www.facebook.com\/GrauZug?ref=br_rs"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate"
},
{
"name": "Accept-Language",
"value": "en-US,en;q=0.8"
},
{
"name": "Cookie",
"value": "datr=pvA2VDnTeMjGlWhVYRrnhBtO; lu=gh2TS-IuZkO-Ku-YhAzkiFIw; p=-2; c_user=100000720140344; fr=07LqqXcCamvBIa9Ww.AWU6e_qoHRglPj51gS-CF6uF-r8.BVY1Qk.DT.FYB.0.AWVvgvJA; xs=79%3A403i2b7V6bYSIA%3A2%3A1439311770%3A8344; csm=2; s=Aa4bsJIf94u-JaGr.BVyieb; presence=EDvF3EtimeF1444749507EuserFA21B00720140344A2EstateFDsb2F1444656454966Et2F_5b_5dElm2FnullEuct2F1444743344BEtrFnullEtwF2707054892EatF1444748467285G444749507665CEchFDp_5f1B00720140344F101CC; act=1444749649564%2F26"
}
],
"requestId": "6724",
"tabId": 93,
"timeStamp": 1444749653175.2,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
onHeadersReceived
{
"frameId": 0,
"method": "POST",
"parentFrameId": -1,
"requestId": "6724",
"responseHeaders": [
{
"name": "status",
"value": "200"
},
{
"name": "cache-control",
"value": "private, no-cache, no-store, must-revalidate"
},
{
"name": "content-encoding",
"value": "gzip"
},
{
"name": "content-security-policy",
"value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;"
},
{
"name": "content-type",
"value": "application\/x-javascript; charset=utf-8"
},
{
"name": "date",
"value": "Tue, 13 Oct 2015 15:20:55 GMT"
},
{
"name": "expires",
"value": "Sat, 01 Jan 2000 00:00:00 GMT"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "public-key-pins-report-only",
"value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\""
},
{
"name": "strict-transport-security",
"value": "max-age=15552000; preload"
},
{
"name": "vary",
"value": "Accept-Encoding"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "x-fb-debug",
"value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q=="
},
{
"name": "x-frame-options",
"value": "DENY"
},
{
"name": "x-xss-protection",
"value": "0"
}
],
"statusCode": 200,
"statusLine": "HTTP\/1.1 200 OK",
"tabId": 93,
"timeStamp": 1444749655679.6,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
onResponseStarted
{
"frameId": 0,
"fromCache": false,
"ip": "31.13.93.3",
"method": "POST",
"parentFrameId": -1,
"requestId": "6724",
"responseHeaders": [
{
"name": "status",
"value": "200"
},
{
"name": "cache-control",
"value": "private, no-cache, no-store, must-revalidate"
},
{
"name": "content-encoding",
"value": "gzip"
},
{
"name": "content-security-policy",
"value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;"
},
{
"name": "content-type",
"value": "application\/x-javascript; charset=utf-8"
},
{
"name": "date",
"value": "Tue, 13 Oct 2015 15:20:55 GMT"
},
{
"name": "expires",
"value": "Sat, 01 Jan 2000 00:00:00 GMT"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "public-key-pins-report-only",
"value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\""
},
{
"name": "strict-transport-security",
"value": "max-age=15552000; preload"
},
{
"name": "vary",
"value": "Accept-Encoding"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "x-fb-debug",
"value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q=="
},
{
"name": "x-frame-options",
"value": "DENY"
},
{
"name": "x-xss-protection",
"value": "0"
}
],
"statusCode": 200,
"statusLine": "HTTP\/1.1 200 OK",
"tabId": 93,
"timeStamp": 1444749655683.3,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
onCompleted
{
"frameId": 0,
"fromCache": false,
"ip": "31.13.93.3",
"method": "POST",
"parentFrameId": -1,
"requestId": "6724",
"responseHeaders": [
{
"name": "status",
"value": "200"
},
{
"name": "cache-control",
"value": "private, no-cache, no-store, must-revalidate"
},
{
"name": "content-encoding",
"value": "gzip"
},
{
"name": "content-security-policy",
"value": "default-src * data: blob:;script-src *.facebook.com *.fbcdn.net *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' *.akamaihd.net *.atlassolutions.com blob: chrome-extension:\/\/lifbcibllhkdhoafpjfnlhfpfgnpldfl;style-src * 'unsafe-inline';connect-src *.facebook.com *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net wss:\/\/*.facebook.com:* https:\/\/fb.scanandcleanlocal.com:* *.atlassolutions.com attachment.fbsbx.com 127.0.0.1:*;"
},
{
"name": "content-type",
"value": "application\/x-javascript; charset=utf-8"
},
{
"name": "date",
"value": "Tue, 13 Oct 2015 15:20:55 GMT"
},
{
"name": "expires",
"value": "Sat, 01 Jan 2000 00:00:00 GMT"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "public-key-pins-report-only",
"value": "max-age=500; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"r\/mIkG3eEpVdm+u\/ko\/cwxzOMo1bk4TyHIlByibiA5E=\"; pin-sha256=\"q4PO2G2cbkZhZ82+JgmRUyGMoAeozA+BSXVXQWB8XWQ=\"; report-uri=\"http:\/\/reports.fb.com\/hpkp\/\""
},
{
"name": "strict-transport-security",
"value": "max-age=15552000; preload"
},
{
"name": "vary",
"value": "Accept-Encoding"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "x-fb-debug",
"value": "fd7Bt\/uIX2rLmngndhprmXlX3mTkZboQqcPSaw9kQt0aQUEfX3ikBMT1016i1c2RPbts9Jhbb0+bVGWPqk\/j7Q=="
},
{
"name": "x-frame-options",
"value": "DENY"
},
{
"name": "x-xss-protection",
"value": "0"
}
],
"statusCode": 200,
"statusLine": "HTTP\/1.1 200 OK",
"tabId": 93,
"timeStamp": 1444749655684.2,
"type": "xmlhttprequest",
"url": "https:\/\/www.facebook.com\/ufi\/add\/comment\/?__pc=EXP1%3ADEFAULT"
}
Any other listener not listed above didn't have output.
Anyone have any idea here?
Your console.log shows that requestBody is not empty.
You'll just have to parse the raw bytes:
If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array.
For example if the posted data is a string then you can get its value in onBeforeRequest listener:
var postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
There are many methods to decode the string depending on the encoding used by the site script.
Another reason why the request body might not be present is because extraInfoSpec must contain 'requestBody' as per below.
chrome.webRequest.onBeforeRequest.addListener(
function(details)
{
console.log(details.requestBody);
},
{urls: ["https://myurlhere.com/*"]},
['requestBody']
);