How to pass post data in http request method - json

The following error prompts when my code executes.
It seems that bodyparameter could not be read.
missing required input JSON parameter requestType.
app.post('/compare', function (req, res, next) {
var options = {
host: 'hostname',
port: 80,
path: '/service',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
},
body: JSON.stringify({
requestType: 'createService'
})
};
var httpreq = http.request(options, function (response) {
response.on('data', function (chunk) {
console.log("body: " + chunk);
});
response.on('end', function() {
res.send('ok');
})
});
httpreq.end();
});

I checked node's http modules latest documentation for request method.
It's options parameter does not accepts any body attribute
There is a example as well which shows that you need to pass body in write method
const postData = JSON.stringify({
requestType: 'createService'
});
const options = var options = {
host: 'hostname',
port: 80,
path: '/service',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();

Related

How to save API Token to use later in Cypress test?

I have this code to use saved API token and use it on other test, but it doesn't work (I get this error message : Reference Error : access_token is not defined: so I need to save my generated token and use it on all my API test
const API_STAGING_URL = Cypress.env('API_STAGING_URL')
describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
method:'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers:{
authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}}).then((response)=>{
expect(response.status).to.eq(200)
const access_token = response.body.access_token
cy.log(access_token)
cy.log(this.access_token)
})
cy.log(this.access_token)
}),
it('Create Cart',function(){
cy.request({
method:'POST',
url: `${API_STAGING_URL}`+"/api/v1/cart",
headers:{
Authorization : 'Bearer ' + access_token,
"Content-Type": 'application/json',
"Cache-Control": 'no-cache',
"User-Agent": 'PostmanRuntime/7.29.2',
"Accept": '*/*',
"Accept-Encoding": 'gzip, deflate, br',
"Connection": 'keep-alive',
"Postman-Token": '<calculated when request is sent>'
},
}}).then((response)=>{
//Get statut 200
expect(response.status).to.eq(200)
//Get property headers
})})
})
This is a scoping issue - access_token does not exist outside of the block where it is created. Filip Hric has a great blog post on using variables with Cypress. My favorite strategy would be to store the value in a Cypress environment variable.
const API_STAGING_URL = Cypress.env('API_STAGING_URL');
describe('Decathlon API tests', () => {
it('Get token', function () {
cy.request({
method: 'POST',
url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
headers: {
authorization: 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
}
}).then((response) => {
expect(response.status).to.eq(200);
Cypress.env('access_token', response.body.access_token);
cy.log(Cypress.env('access_token'));
});
});
it('Create Cart', function () {
cy.request({
method: 'POST',
url: `${API_STAGING_URL}` + '/api/v1/cart',
headers: {
Authorization: `Bearer ${Cypress.env('access_token')}`,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'User-Agent': 'PostmanRuntime/7.29.2',
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br',
Connection: 'keep-alive',
'Postman-Token': '<calculated when request is sent>'
}
}).then((response) => {
// Get statut 200
expect(response.status).to.eq(200);
// Get property headers
});
});
});
Another approach would be to create the access_token in a hook and then you can access it in a it() block.
There are a few ways to do it.
Using variable:
let text
beforeEach(() => {
cy.wrap(null).then(() => {
text = "Hello"
})
})
it("should have text 'Hello'", function() {
// can access text variable directly
cy.wrap(text).should('eq', 'Hello')
})
Using an alias:
beforeEach(() => {
cy.wrap(4).as("Number")
})
it("should log number", function() {
// can access alias with function() and this keyword
cy.wrap(this.Number).should('eq', 4)
})
Here is a working example.

Unexpected token < in JSON at position 4 - when fetch link Ajax [GAS]

First, I have to apologize for my poor English skill I am using Google Apps Script.
I'm trying to get JSON data from AJAX link but sometimes error occurs
Unexpected token < in JSON at position 4
I know the problem here is the data return form "HTML" while i expect "JSON"
I trying
My Script
async function getJSON () {
const myHeaders = {
'cache' : 'no-cache',
'pragma': 'no-cache',
'Cache-Control': 'no-cache',
'accept': 'text',
'dataType' : 'text',
'contentType': 'application/json; charset=utf-8',
};
const myInit = {
muteHttpExceptions: true,
method: 'GET',
headers: myHeaders,
};
const url = "https://www.xxxx.xxx/xxxxxxx/?ajax=xxxxxxx"
const content = await UrlFetchApp.fetch(url ,myInit).getContentText();
const obj = JSON.parse(content);
....
...
}
The problem as you say is that sometimes the response is an HTML, which generates that when the JSON.parse function is called, an error arises because the response does not contain a valid JSON.
This error comes from the server, so there is not much you can do about it. One way to handle the error is with a try-catch block, which is common practice in asynchronous fetch.
For example:
async function getJSON() {
try {
const myHeaders = {
'cache': 'no-cache',
'pragma': 'no-cache',
'Cache-Control': 'no-cache',
'accept': 'text',
'dataType': 'text',
'contentType': 'application/json; charset=utf-8',
};
const myInit = {
muteHttpExceptions: true,
method: 'GET',
headers: myHeaders,
};
const url = "https://www.xxxx.xxx/xxxxxxx/?ajax=xxxxxxx"
const content = await UrlFetchApp.fetch(url, myInit).getContentText();
const obj = JSON.parse(content);
// ...
} catch (err) {
console.log({
err
})
}
}

Network Error making post request using Axios

I'm trying to make my application sending a post request and receiving a response using Axios. However i encoutered errors while trying to make a post request.
My code for making post request:
onPostJson = () => {
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi',
{
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
})
.then((response) => {
console.log(response.json());
}, (error) => {
console.log(error);
});
};
Error:
Network Error
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:80:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
I suspected that there is problem with the URL, but i successfully made a post request to this URL using Postman.
Solution: It was syntax error. I forgot to include Header configurations in the code.
onPostJson = () => {
console.log("onpost");
axios.post('http://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
FromDate: "01-Jan-2020",
ToDate: "01-May-2020",
}, {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImtpZW50ZC5haXRzIiwibmJmIjoxNTkzNzY0MDU0LCJleHAiOjE1OTQzNjg4NTQsImlhdCI6MTU5Mzc2NDA1NH0.liIM6g2E_EMXvnRpL1RcU-QVyUAKYxVLZZK05OqZ8Ck',
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(respond => {
// console.log(respond.data.CaThuHoiList);
setShiftData(respond.data.CaThuHoiList);
})
.catch(function (error) {
console.log('Error');
console.log(error);
});
}
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
});
i'm not sure, but ..
Do you want to try it like the code above?

React Native - Parsing error from JSON Response

Here is my code.
I am calling the following function to get state list.
callGetStatesApi()
{
callGetApi(GLOBAL.BASE_URL + GLOBAL.Get_States)
.then((response) => {
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
});
}
Here is common callGetApi function for getting response from GET Api.
export function callGetApi(urlStr, params) {
return fetch(urlStr, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = responseData
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
I am getting the following error.
Alert only show the string , but your case "stateArray" is complex object (array,structure..)
So use stateArray.toString() or JSON.stringify(stateArray),
Or
Try the below method and let me know,
fetch(GLOBAL.BASE_URL + GLOBAL.Get_States, {
method: 'get',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',}
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData) // this is the response from the server
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
}).catch((error) => {
console.log('Error');
});

why it's appending #/... in location.hash

I am using angular js for my app.
Here , My Angular code as :
var app = angular.module('TaskManager', ['ngCookies']);
app.controller('LoginController', function($scope, $http, $location, $cookieStore) {
$scope.login = function(str) {
console.log(".......... login called......");
$http({
method: 'POST',
url: '../TaskManager/public/user/login',
data: $.param({
email: email.value,
password: password.value
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
var result = data.response;
console.log(result);
if (result == "success") {
//storing value at cookieStore
$cookieStore.put("loggedin", "true");
$cookieStore.put("loggedUserId", data.user_id);
$cookieStore.put("password", data.password);
$cookieStore.put("type", data.type);
$cookieStore.put("email", data.email);
location.href='Dashboard.html';
} else alert(data.message);
});
});
app.controller('DashboardController', function($scope, $http, $location, $cookieStore) {
$scope.users = [];
$http({
method: 'POST',
url: '../TaskManager/public/task/tasklist',
data: $.param({
logged_userid: userId,
password: password,
status: 'All',
user_id: useridToFetch
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
$scope.users = data.users;
});
//location.hash="";
console.log(window.location);
});
It works fine but when it redirects to the dashboard page after logged in, the location.hash is being assigned with the #/PAGE_NAME. it becomes location.hash=#/PAGE_NAMEwhich results the URL value repetition.
Like:
http://localhost:8085/NovaTaskManager/Dashboard.html#/Dashboard.html
I tried to clear hash at DashboardController, Which clears for a while but as soon as the page is refreshed the earlier URL appears again.
Don't know:
1. why location.hash is getting assigned by default ?
2. How it can be resolved ?
Any suggestion would be appreciated.