Matching axios POST request with moxios - javascript

Is it possible to use moxios to mock a reply to a POST request that will match not just by URL but also by the POST body? Inspecting the body afterwards would work for me too.
This is what I am doing now. As far as I know there are no method specific stubbing methods:
describe('createCode', function () {
it('should create new code', function () {
moxios.stubRequest(process.env.API_URL + '/games/GM01/codes', {
status: 200
})
})
})

There is a way to inspect the last axios request using moxios:
let request = moxios.requests.mostRecent()
expect(request.config.method).to.equal('post')
expect(JSON.parse(request.config.data)).to.deep.equal(code)
The config object is what's being passed in axios, data is the body of the request.

Related

Axios POST to endpoint, returns OPTIONS request

I am trying to make a post request from a form to an endpoint, the form works fine, and the db too. The main issue is that i am posting to this endpoind localhost:3001/professional with the body of the form as data
export const postPro = (data) => async () =>{
console.log(data)
axios({
method: 'post',
url: "http://localhost:3001/professional",
data: data
})
}
data itself is an object. This is what i get from the console after i press send:
console of backend returning options, I did the first 2 post with postman to see if it works the db, and indeed it does.
I am using Redux toolkits(first time i use it) and React Native
I try rewriting the post, like this:
axios.post("http://localhost:3001/professional", data)
then i try to console.log the data to see if reaches the axios.post and it does, i can see the log of the object data in the console.
Also i was thinking that has something to do with async await so i try to play with that a little, and it's the same result.

Returning Data from express server | function call?

I am trying to return a response from a backend server, of technologies that match a specific url which is searched on the front end.
My form will submit, and the URL will change, but no results will come through, and no errors appear in the console.
My front end script tag is as follows:
function Submit () {
e.preventDefault();
const formResult = new FormData(form);
const url = '/' + encodeURIComponent(formResult.get('search'));
const button = document.getElementById('search');
const sendHttpsRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data ? {'Content-Type': 'application/json'} : {}
}).then(response => {
if (response.status >= 400) { //response okay
return response.json().then(errResData => {
const error = new Error('Something went wrong');
error.data = errResData;
throw error;
});
}
return response.json();
});
};
const getData = () => {
sendHttpsRequest('GET', '/:url').then(responseData => {
console.log(responseData);
});
};
button.addEventListener('search', getData);
}
Is there something here I am missing? I think it might be a function call, but do I also need to include a function call when I am sending an HTTP request? Where would the function call go in this case? What would it look like?
You have lots of problems with this.
You call getData when a button is clicked, but only if that button is clicked after Search is called. You never call Search.
The first thing Search does is call e.preventDefault, but e isn't defined anywhere.
You create formResult from a variable called form which you never define
You create formResult when Submit is called but it looks more like something you want to do when getData is called
You set the body of the request with JSON.stringify(data), but you've never defined data … and if you intended to say formResult then that would be a FormData object which won't convert to JSON.
When you send the request you sent it to '/:url' which uses Express parameter syntax … but this is the client-side code so you need to put the actual data there.
You define a variable url in Submit but then you never use it (probably you intended to use it in 6 but forgot and hardcoded a string that didn't make sense instead).
You are trying to set a body on a GET request
You seem to have thrown a lot of code together without testing it as you went along.
I recommend starting from scratch.
Write a function to be called when you click the button. Have it just prevent the default behaviour and log something to the console.
Then fetch the form data you want and log that.
Continue to work from there, testing each stage as you go along so you can detect the mistakes like these.

GET request working through Postman but the browser tells me GET request cannot have body

I'm simply trying to send some urlencoded parameters via a GET request using fetch. I'm just trying to print the parameters using Express at the moment, like so:
app.get('/api', function (req, res) {
console.log(req.body);
res.sendStatus(200);
return;
});
This works just fine in Postman using a GET request and x-www-form-urlencoded key-value pairs. The webserver will print all the key-value pairs just fine.
But when I try and use fetch to do the exact same thing I get nothing but problems. I've tried two different methods:
fetch(`http://localhost:3000/api?user=test&password=123`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
The request does go through using this method, but the webserver only prints {} - an empty object.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("user", "test");
urlencoded.append("password", "123");
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: urlencoded,
};
fetch("localhost:3000/api", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The request does not go through using this method, and the browser gives me the error TypeError: Window.fetch: HEAD or GET Request cannot have a body.
This code was generated using the request that works in Postman using the generate code snippets option.
What am I doing wrong?
The parameters in this URL:
http://localhost:3000/api?user=test&password=123
are in the query string, not in the body and thus the content-type does not apply to them - they are properly encoded to be in a URL. In Express, you would access these with req.query. You should see a value for req.query.user and req.query.password in your Exprss request handler.
Note, it is not recommended that you send user credentials in a URL like this because URLs are often present in log files at your ISP, at the recipient server, in proxies, in your browser history, etc... User credentials like this should be sent in POST request over https where the credentials would go encoded in the body (where it won't be logged or saved by intermediaries).
The fetch error is accurate. GET requests do not have a body sent with them. That would be for POST or PUT requests. A GET request is a "get" request for a resource that you specify only with a URL.
You're confusing request body with a query string.
Your second request (you don't need a Content-Type for it)
fetch("http://localhost:3000/api?user=test&password=123");
would be handled by the following Express function:
app.get('/api', function (req, res) {
console.log(req.query); // Note that query, not body is used.
res.sendStatus(200);
return;
});
You can access fields from the query object as req.query.user && req.query.password.
As for having a request body in a GET request: while RFC doesn't explicitly fordbid it, it requires server to not change response based on the contents of the body, i.e. the body in GET has no meaning in the standard, so JS HTTP APIs (both fetch & XmlHttpRequest) deny it.
firstly if you are trying to get some data from your API or others API you should do GET request in order to get your desired data from server for example, if you want to get a specific things like a user or something else you can pass your data in GET request URL using query string or route params.
secondly, if you want to authenticate and send your credentials to the server its not recommended to use GET request as i said earlier GET request simply is for fetching some data from server, so if you want to send your credential or anything else you are better off using POST request to send data to the server and you can't do POST request in the browser, so you have to use something like postman or insomnia in order to send your POST request to the server. i hope it could help you to solve your issue.

post request help angular2

I am trying to do a post request to get a token that will let me have access to an access token. Whenever I try to post to it I get an error that the access_token property can't read something that is undefined. I am pretty sure this means that my post request isn't working and I don't know why. I think it has something to do with my post parameters and the map and subscribe methods. I just don't know how to fix them. Any help would be appreciated, thanks.
This is my code for the post request.
httpPostRequest() {
this.grabState();
this.grabCode();
this.grabSessionStorage();
this.grabTokenUri();
this.grabClientId();
this.grabSecret();
this.grabServiceUri();
this.grabRedirectUri();
this.data = {
code: this.code,
grant_type: 'authorization_code',
redirect_uri: this.redirectUri,
};
const headers = new Headers({'Accept': 'application/json'});
const options = new RequestOptions({ headers: headers });
return this._http.post(this.tokenUri, this.data, options)
.map((postResponse: Response) => postResponse.json())
.subscribe(resPostResponse => (this.postResponseJson = resPostResponse));
}
Angular HttpClient is asynchronous, so you have to subscribe to your post request (in your view for example).It's now returning undefined because it's not executed yet. You can use a callback to execute an another function after getting the token.

Koa cookie returning `undefined`

After a POST request is sent from the browser to the /generate url in the server, I want to create a string and save it as a cookie. When a GET request is later sent from the browser to the /retrieve url in the server, I want to send that string as a response to the client.
Here is what I tried:
routes.js
const Router = require('koa-router')
const router = new Router()
router.post('/generate', function * () {
this.cookies.set('generatedString', 'example')
this.response.body = 'String saved as cookie!'
})
router.get('/retrieve', function * () {
const cookie = this.cookies.get('generatedString')
console.log(cookie) // undefined!
this.response.body = cookie
})
Why does doing this.cookies.get('generatedString') return undefined even though the POST request handler has already run and should have set that cookie? Any help would be appreciated!
EDIT: In case it is of importance, I thought it would be worth mentioning that I am using the fetch API to make the POST and GET requests.
In case it is of importance, I thought it would be worth mentioning that I am using the fetch API to make the POST and GET requests.
The fetch API mentions that "By default, fetch won't send any cookies to the server, resulting in unauthenticated requests if the site relies on maintaining a user session."
If you want fetch to send cookies, you will need to add an option to the request you send out called credentials and set it to a value of include.
Example POST request:
const request = {
method: 'POST',
credentials: 'include',
headers: ...,
body: ...
}
fetch('/generate', request).then(...)
Example GET request:
fetch('/retrieve', { credentials: 'include' }).then(...)

Categories

Resources