post method not working phantomjs2 - http-post

my header is
var headers = {
'Content-Type': 'application/json'
}
and data is
data = '{"mydata": "foo"}';
and code is
page.open('my site url', 'POST', data, headers, function (status) {
var jsonSource = page.content;
console.log(jsonSource);
phantom.exit();
});
but in onResourceRequest my method is 'GET'
what is problem ?

Related

Cypress: How do I pass a selected property from API response to another API request?

I would like to use Cypress for API testing. My goal is to extract a part of the API response and pass it to another API request. Here's a sample code:
Cypress.Commands.add('createCustomer', () => {
return cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
return new Promise(resolve => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
resolve(memberId)
return memberId
})
})
})
With this code, I am getting [object%20Object] as the result.
Hoping for some feedback.
So you are adding the id generated by the POST to a subsequent GET request?
Try returning the id without using a Promise, I don't think you need one at that point since the response has already arrived.
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id;
return memberId;
})
Url for GET
cy.createCustomer().then(id => {
const url = `api/v1/Customers${id}`;
...
or
cy.createCustomer().then($id => {
const id = $id[0]; // Not quite sure of the format, you may need to "unwrap" it
const url = `api/v1/Customers${id}`;
...
If you want to pass response from API Request 1 to API Request 2, you can do something like this:
describe('Example to demonstrate API Chaining in Cypress', function () {
it('Chain two API requests and validate the response', () => {
//Part 1
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=sn',
}).then((response) => {
const location = response.body[0].title
return location
})
//Part 2
.then((location) => {
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=' + location
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body[0]).to.have.property('title', location)
})
})
})
})
Your code seems to be failing during the initial request, not during the subsequent actions. I am far from a Javascript expert, but you seem to have some unnecessary complexity in there. Try simplifying your command like this and see if you can at least get a successful request to go through:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
})
})
And if that works, keep going:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
return memberId
})
})

Laravel Forbidden Access when using Ajax

I installed a fresh Laravel App with authentication. I am using laragon. The login, registration, reset password pages are working fine. I created a profile controller for the user to edit profile. However, when submitting the form through Ajax, it gives me a Forbidden - You don't have permission to access / / /profile/edit_profile on this server..
class ProfileController extends Controller
{
//
function index()
{
return view('profile.index');
}
function edit_profile(Request $request)
{
$txt_midname = $request->input('txt_midname');
$txt_firstname = $request->input('txt_firstname');
$txt_lastname = $request->input('txt_lastname');
$extname = $request->input('extname');
$user = Auth::user();
$user->firstname = $txt_firstname;
$user->midname = $txt_midname;
$user->lastname = $txt_lastname;
if ($user->save()) {
return 'ok';
}
}
}
Here is also the route:
Route::post('/profile/edit_profile', 'ProfileController#edit_profile')->name('edit_profile');
and the view:
$('#btn_update').on('click', function() {
var btn_text = $('#btn_update').text();
var txt_firstname = $.trim($('#txt_firstname').val());
var txt_midname = $.trim($('#txt_midname').val());
var txt_lastname = $.trim($('#txt_lastname').val());
var extname = $.trim($('#extname').val());
$.post(baseUrl + '/profile/edit_profile', {
'_token': token,
'txt_midname': txt_midname,
'txt_firstname': txt_firstname,
'txt_lastname': txt_lastname,
'extname': extname
}, function(data) {
if (data == 'ok') {
window.location.reload();
}
})
})
You need to inject the csrf token to your request.
$.post({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/gallery/create/ajax',
data: {},
method: 'POST',
success: function(response) {
},
error: function(error) {
}
})
or if you want every ajax request inject the csrf token you can do this as well.
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
It was my mistake. The problem is with my baseUrl in javascript. It should be var baseUrl = "{{url('')}}";instead of var baseUrl = '{{url('')}}';

Return Body Text from Fetch API

I would like to return the response body text returned by the POST that I send by fetch.
var r = '';
var res = fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
return response.text().then(function (text) {
r = text;
})
});
Neither r or res is returning the body text. They are both returning Promise. How do I only return the body text?
I was able to get the response body text by using await.
const response = await fetch(this.commentsUrl, {
method: 'post',
body: JSON.stringify(comment),
headers: {
'Content-Type': 'application/json'
}
});
const text = await response.text();

405 error while calling webapi get method using ajax

I developed a WebApi and Client page for testing.
Here is my controller
public class CarDetailsController : ApiController
{
// GET api/cardetails
[HttpGet]
public IEnumerable<CarsStock > GetAllcarDetails()
{
CarsStock ST = new CarsStock();
CarsStock ST1 = new CarsStock();
List<CarsStock> li = new List<CarsStock>();
ST.CarName = "Maruti Waganor";
ST.CarPrice = "4 Lakh";
ST.CarModel = "VXI";
ST.CarColor = "Brown";
li.Add(ST);
ST1.CarName = "Maruti Swift";
ST1.CarPrice = "5 Lakh";
ST1.CarModel = "VXI";
ST1.CarColor = "RED";
li.Add(ST1);
return li;
}
}
and here is my ajax call
<button onclick="AllcarDetails()"></button>
<script type="text/javascript">
function AllcarDetails()
{
$.ajax({
type: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType: 'application/json',
url: "http://localhost:1822/api/cardetails", //URI
success: function (data) {
debugger;
var datadatavalue = data;
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
It gives 405 Method Not Allowed error all the time.I tried by googling but cannot find the exact situation.Can somebody help me to solve this?
Got result correctly while calling from browser 'http://localhost:1822/api/cardetails'
Did you check so that HTTP Activation is activated where you run this code?

Angular Datatables use source object

With Angular Datatables I want to pre-load a JSON object with Ajax so that I can re-use the object elsewhere without doing another ajax request.
But how do I load this object into the datatable?
.controller('ResponsiveDatatableCtrl', function ($scope, $rootScope, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $state, $http) {
$scope.dataLoading2 = true;
var vm = this;
var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
var url = apiserv+"api.files.php"+data;
var headers = {'Content-Type': 'application/x-www-form-urlencoded'};
$http({
method: 'POST',
url: url,
headers: headers,
})
.success(function (response) {
$rootScope.globals.files = response;
$scope.dataLoading2 = false;
//console.log($rootScope.globals.files);
});
vm.dtOptions = DTOptionsBuilder.fromFnPromise($rootScope.globals.files)
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);
})
Ok I have attempted the following and it seems to call my code under success but then the table doesn't update?
vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: url,
type: 'POST',
headers: headers,
data: function(data, dtInstance) {
},
success: function(response) {
$rootScope.globals.files = response;
}
})
.withPaginationType('full_numbers')
.withBootstrap()
.withOption('responsive', true);

Resources