I have a problem sending json data to my node server
I tried
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data: {test:"test"}
};
when I console.log() req.body y have
{ '{"test":"test"}': '' }
When I try with
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
data: 'test=test'
};
I have a good result on the server
I set the content type to application/x-www-form-urlencoded to allow the cross domain
On the server I have
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Thanks for the help
If you want to send it as JSON, then you may consider doing so:
var req = {
method: 'POST',
url: 'http://33.33.33.15/user/signin',
headers : {
'Content-Type' : 'application/json'
},
data: JSON.stringify({ test: 'test' })
};
Related
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.
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
})
}
}
I am using AngularJS to send the array element to my Node.js where I need to do some process. Everything works fine when the array size I am sending is small but if I try to use the array which is of 200 sizes then I get the error 431 (Request Header Fields Too Large). How can I resolve this issue? I cannot spit my array.
var data = JSON.stringify({
input : $scope.input,
Input1 : $scope.Input1,
Input2 : $scope.Input2,
Input3 : $scope.Input3
});
$http({
url: "/createEvents",
method: "POST",
headers: {'Content-Type': 'application/json; charset=utf-8'},
params: {data:data}
}).success(function(response) {
console.log(response)
}).error(function(error) {
console.log(error)
});
I am not understanding how to fix this issue.
$http({
url: "/createEvents",
method: "POST",
headers: {'Content-Type': 'application/json; charset=utf-8'},
data:data // check this line.
}).success(function(response) {
console.log(response)
}).error(function(error) {
console.log(error)
});
I'm stuck at this point of my code wherein I have successfully called the Sheets API using PUT request, but it's not rendering on the Google Sheet.
Here is my code where I use both PUT and GET requests to see if the data changed:
background.js
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) {
console.log('this is the token: ', token);
var params = {
"range":"Sheet1!A1:B1",
"majorDimension": "ROWS",
"values": [
["Hi","Crush"]
],
}
let init = {
method: 'PUT',
async: true,
data: params,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1?valueInputOption=USER_ENTERED",
init)
.then((response) => console.log(response))
let request = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1",
request)
.then((response) => response.json())
.then(function(data) {
console.log(data)
});
}
Here's the screenshot of my Google Sheet, the data didn't change. The status of the PUT request is 200 and it seems the data is still Hello World in A1:B1:
Here's the log:
Do you have any idea what's missing here?
How about this modification? Please modify the object of init as follows.
From:
data: params,
To:
body: JSON.stringify(params),
Reference:
Using Fetch
For a service called mOTP, I need to send a parameter with name 'private'. Here is my Parse cloud code.
var phnNum = request.params.phnNum;
var validationParams = {"private":"MyPrivateKey"};
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.mOTP.in/v1/otp/MyAPIKey/'+MySessionID,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: validationParams,
success: function(httpResponse) {
console.log(httpResponse.data.Status);
console.log(httpResponse.data.Result);
if(phnNum == httpResponse.data.Result) {
response.success("Success");
} else {
response.error("phnNum not matched");
}
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error("URL hit failed");
}
});
The mOTP service gives response in JSON. But always I am getting the response as 'Method not supported'. I am not able to find where I am doing mistake. Please help.
mOTP docs: http://dial2verify.com/mOTP_Missed_Call_OTP_Authentication/Documentation.html
First of all, You should pass a body message with the POST method.
The content-type should be 'application/x-www-form-urlencoded' according to the documentation.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://motp.p.mashape.com/v1/otp/{APIKey}/{SessionId}',
headers: {
'X-Mashape-Key': 'YOUR-X-Mashape-Key',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {'private': 'Your_mOTP_Private_Key'},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error("error: " + httpResponse.status);
}
});