How to "intercept" a request that is made with cy.request with cypress - request

As far as I understand cy.intercept() can be used to stub requests that the application itself makes.
Now I have a HTTP POST request with cy.request() in one of my custom commands in Cypress. Because this is a request made by cy.request() function I can't use cy.intercept() to stub the response of this request.
Is there any workaround to stub a respons of a request made with cy.request() ?
Now I have the following which is logging the real response correctly, but I want to keep this response even the when the remote server is offline:
cy.request({
method: 'POST',
url: 'https://sample.com/token',
body: {
username: "UserNameSample",
password: "PasswordSample"
},
form: true,
}).then(response => {
cy.log(JSON.stringify(response.body))
})
Which is resulting in the following printscreen of the comment log in cypress.:

You can try for fetch interface to make the network calls instead:
cy.intercept({
method: 'POST',
url: 'https://sample.com/token',
},
{
// your stubbed response
}).as('createToken').then(() => {
fetch('https://sample.com/token', {method: 'POST'})
.then((response) => {
cy.log(JSON.stringify(response.body))
})
})
cy.wait('#createToken').its('response.body')
P.S. I've not tested it, so it might need some adjustments

Related

Expressjs Server cannot handle Requests from the Outside

I have a ExpressJs Server with React Components. And the Server should handle Requests from Outside and one request should play a Song from the Spotify API when not currently playing.
app.post("/play", (req, res) => {
try {
// requesting to play uses query params
id = req.query.id;
currPlayingID = 0;
// get the currently playing song from the SPotify API
axios({
url: "https://api.spotify.com/v1/me/player/currently-playing",
method: "get",
headers: {
authorization: `Bearer ${access_token}`,
},
})
// set the currently Playing ID or to zero if nothing is playing
.then((response) => {
if (response.data !== null) {
currPlayingID = response.data.id;
} else {
currPlayingID = 0;
}
});
// only play the song if its not currently playing
if (id !== currPlayingID) {
// making a axios request to the Spotify API to play the Song with the ID
axios({
url: "https://api.spotify.com/v1/me/player/play/",
method: "put",
headers: {
authorization: `Bearer ${access_token}`,
},
data: {
uris: [`spotify:track:${id}`],
},
});
res.status(204);
}
} catch (error) {
res
.status(404)
.json({ message: "Couldn't get Info from Spotify API", error: error });
}
});
The Problem:
The Code works when I start the server on the device itself (so a local server on my Desktop PC), but when I start the Server on my RaspberryPI i cannot handle Requests to this endpoint /play. Yeah I updated all the IP Adresses, everywhere.
But the moer ointeresting part is using the React Client I get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
Requesting with POSTMAN I get the following:
Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource
And from a request using a python script I get on the server side:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 400".] {
code: 'ERR_UNHANDLED_REJECTION'
}
I have no clue how to fix each error and if it is one fix. Basically I found out it is a Problem with rejeccting requests from outside localhost, because with cURL on my ssh terminal it works.
I'm learning express, so I m not an expert, but I'm looking at your errors. I will suggest you try asyncHandler module. It handles asynchronous requests and exceptions.
I faced a similar issue because while I'm sending the API request via
Axios, my token is null/empty/wrong, so make sure your token is correct
this is my request format
axios({
method:"POST",
url:"https://graph.facebook.com/v13.0/"+phon_no_id+"/message?access_token="+token,
data:{
messaging_product:"whatsapp",
to:from,
text:{
body:"Hi.. I'm Prasath"
}
},
headers:{
"Content-Type":"application/json"
}
});

Refused to connect to GET request

I use an oodrive_sign service which hosts my code and which allows me to use an electronic signature
I work on AngularJS and I want to make a HTTP request.
It works locally, but in production I have this error:
ERROR
My request :
const getReq = {
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/todos/1',
//headers: { 'Content-Security-Policy': 'default-src'}
};
$http.get(getReq).then(function(response){
console.log(response)
},function(err) {
console.log(err)
})
I dont know if it's my bad or if it's an error related to the oodrive service
I would like to know if I have to do anything in particular before I call them again.
Thanks

How to send a POST request with variables in React?

I am learning how to send a POST request to an API with React.
What I'm trying to achieve right now is sending a POST request to an API.
The API will insert the event with something like this (what is this method called?):
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
The method that I'm currently using as POST is shown at POST method and it returns me with the error unexpected token '<' in json at position 0 and the result that I get when I console.log(JSON.stringify(event)) is something like this:
{"event_id":"5","desc":"<p>HelloWorld</p>","name":"testing"}```
POST method
const response = await fetch('https://api.com/WebService.asmx/insertEvent',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
})
Edit: I've fixed the above error by encoding the HTML that I need to send. This is now my latest POST method, but I'm still facing error 500 for some reason even though it works when I copy and pasted the URL+params from the console.log that has the error shown:
const addBulletin = async (event) => {
console.log(event, '--event')
const url = 'https://api.com/WebService.asmx/insertEvent';
axios.post(url, null, { params: {
title: event.title,
desc: event.desc,
image: event.image,
employee: event.employee,
entity: event.entity,
startDate: event.startDate,
endDate: event.endDate,
createdBy: event.createdBy
}})
.then(response => console.log(response.status))
.catch(err => console.warn(err));
};
Edit: I've tested the API on a vanilla JS project using .ajax with POST, and it works, so I think the API shouldn't be a problem.
var json = $('.insert-form').serialize();
$.ajax({
type: "POST",
url: "https://api.com/WebService.asmx/insertEvent",
data: json,
async: true,
success: function (response) {
alert("Event has been successfully created!");
},
error: function (response) {
console.log(response);
}
});
The API you are sending the request to expects a query parameter (data in the URL).
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
In this request, we are sending 3 query params: event_id, desc, and name.
To send this kind of request from React, you should not use request body. Instead. I advise you to use axios to make it easier. It's a very powerful library, better than using fetch. It should be done this way:
axios.post(`https://api.com/WebService.asmx/insertEvent`, null, { params: {
event_id: eventId,
desc
}})
.then(response => response.status)
.catch(err => console.warn(err));
This may help: How to post query parameters with Axios?

Angular $http post call passing data issue to GO backend

I am trying to get access to backend written in GO which in 99% is good (problem does not lay there).
For now I just created simplest call which stay in controller (it will be in service in future) to register new user. Although I hardcoded data which I am passing the response says 403 forbidden. In powerShell shows reason of 403:
RegistrationForm parse - email: , nick:
Validation failed for email - blank
It looks like I am not passing my data correctly because email is blank. Please take a look at my code:
$ctrl.fake_registerSubmit = function() {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
data: {
email: 'check#onet.pl',
nick: 'borysxoxo',
password: 'admin12312',
password_confirmation: 'admin12312'
}
})
.then(function successCall(response, post) {
console.log('user added');
}, function errorCall(respone) {
console.log('error callback');
console.log(respone);
})
};
This screenshot presents API documentation which I am trying to access:
link
What am I doing wrong? Is there other way to pass data?
You are sending some json data with the wrong Content-Type.
I see 2 options, either change Content-Type in your header to:
'Content-type' : 'application/json'
or transform your payload to:
data: "email=check#onet.pl&nick=borysxoxo&password=admin12312&password_confirmation=admin12312"

React + fetch request

I am reading this article fetch API and trying to understand how to work with fetch in React. Firstly, could you explain what is request headers ?
Than,
in angular we do something like:
$http.get('/someword').success(function(response) {
console.log('i got the data i requested');
var variable = response;
}
and than on server side in express I can write:
var app = express();
app.get('/thissomeword', function(req, res) {
console.log('I got a GET request')
res.json(someVariableWithData)
})
How to do the same with fetch ? And the main question where and when I need to do it ? I understand that i need after i get data to do this.setState({}) for using my data later, but HOW is for me huge conundrum.
Here you have great facebook documentation:
https://facebook.github.io/react-native/docs/network.html
with example that shows what you want
headers in request
Sometimes you need header in request to provide access token or content-type (especially in POST request)
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Promises instead of callbacks
In your example you pass callbacks (req and res) to your request, in fetch you have Promises so you get response as a paramether of then or error message in catch.
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
Request Headers
As basic, Request Headers are set by the browsers and the application developers, this is use to tell the web server what the client is sending and what can it accept back in return.
Reference
Fetch
Fetch is used to make async network calls. It has a simpler API support based on promises. I'll make your code cleaner with less number of lines.
Reference

Resources