I have an api which I'm supposed to send a specific id as parameters to, so that it returns data based on the filtered list.
I tried to send it as :
await this.$store.dispatch("axiosGet",
{url: 'folder/api/property-walls'}, {propertyEid: this.id}).then(response => {
if (response.status === 'error') return
this.wallList = response.data.data.data
})
but it doesn't make any differences.
my API recieves sth like this.
can anyone help me out with the solution?
you can use params in your get requst
this will work!
axios.get('/api', {
params: {
foo: 'bar'
}
});
from this refrence
Axios get in url works but with second parameter as object it doesn't
Related
I'm working with React.js and I have the following problem:
import axios from "axios";
export default function Home() {
const [products, setProducts] = useState([]);
const ax = axios.create({ headers: { Accept: 'application/json' }});
function test() {
const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => {
// expected the setProducts to be filled with the return of this request
setProducts(response.data);
});
}
test();
// and when I get here to see if the products have been filled, I get an empty array [ ]
console.log(products);
/*
as the products variable was not filled within the axios promise by setProducts,
there is no way to throw the products array here in the HTML to make a forEach or
a map to look cute together with the tags
*/
return (
<sup>how sad, with the product array empty, I can't put the data here '-'</sup>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
See how the result comes out in the IDE console:
I'm in Visual Studio not knowing what to do, I'm new to ReactJS with NextJS and from an early age I've been trying to see if I could solve this problem, but without success.
What can I do to bring the products to the HTML page?
UPDATE: As per the solution below, I created a possible workaround that indicates a path that could have returned a solution
ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {})
.then((response) => setProducts(response.data))
.catch((error) => {
console.log(error); // AxiosError {message: 'Network Error', name: 'AxiosError', ...}
console.log(error.status); // undefined
console.log(error.code); // ERR_NETWORK
});
useEffect(() => {
console.log(products);
}, []);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.2/umd/react-dom.production.min.js"></script>
and I'm getting the same error that I put in the comments of the first answer below:
but when I change the setProducts by the console.log to see if it returns the same result, this appears in the terminal where my next.js application is running
that:
ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {})
.then((response) => console.log(response.data.length)) // returns the length of the products array
returns this when I update my app:
NOTE: That's why I'm not able to understand my application in Next.js. I'm following all the correct guidelines, writing the code perfectly using axios and when I run the application on the website it gives a network error and doesn't show exactly the amount of products that were displayed in the terminal where my application is running.
I've already configured all the request headers correctly, enabling CORS to allow external requests with other API's, and I still don't succeed in returning the data to my application's page.
Wrap the stuff you have to fetch products inside useEffect hook
useEffect(()=>{
const ax = axios.create({ headers: { Accept: 'application/json' }});
function test() {
const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => {
// expected the setProducts to be filled with the return of this request
setProducts(response.data);
console.log(response.data)
});
}
test();
},[])
Then in your return of the component, you can use map on products array with null and undefined checks
Like
{products && products.map(product=>{})}
i have cypress request call returning Json array
{ids:[one, two, three]}
How can i parse out one of the array values from the body of response and pass it to the next test?
Considering the given information I guess what you want is Asserting Network Calls from Cypress Tests.
There is a good example in the cypress-example-recipes
I guess you could do something like
describe('Test', () => {
let ids;
it('gets expected response', () => {
cy.server()
cy.route('GET', '/url').as('response')
cy.visit("url")
// log the request object
cy.get('#response').then(console.log)
// confirm the request status
cy.get('#response').should('have.property', 'status', 200)
// confirm the request's response
cy.get('#response').its('response').then((res) => {
expect(res.body).to.deep.equal({
"ids": ["one", "two", "three"]
})
// store the ids in a variable
ids = JSON.parse(res.body)?.ids
})
})
})
In Cypress there is possibility to stub XHR response, but I wanted to catch and modify JSON response.
https://docs.cypress.io/guides/guides/network-requests.html#Stub-Responses
https://docs.cypress.io/api/commands/route.html#With-Stubbing
I do not find a good example that explain this.
In my app there is a call to an API:
/isHuman
and response is:
{"isHuman":true}
I wanted to intercept this call and put true and another test with false
can anybody provide this ?
Last Edit:
Testing app in on localhost(where I define baseURL - localhost:3123), but there are api calls to a different domain(https://api.app.com/isHuman).
I need to change response from that xhr call.
You can redefine the same url multiple times inside the same it():
it('should od whatever', () => {
cy.route('GET', '/isHuman', { "isHuman": true });
/* trigger some requests */
cy.route('GET', '/isHuman', { "isHuman": false });
/* trigger other requests */
});
it('modifies the response from the server to insert Kiwi', () => {
cy.intercept('favorite-fruits', (req) => {
req.reply((res) => {
// add Kiwi to the list received from the server
console.log('original response from the server is %s %o', typeof res.body, res.body)
const list = res.body
list.push('Kiwi')
res.send(list)
})
})
cy.visit('/')
// check if Kiwi is the last fruit
cy.get('li').should('have.length.gt', 3)
.last().should('contain', 'Kiwi')
})
below is the source of the code:
Partial route mock
I'm using the fetch-api for the first time and having trouble passing a non-stringified JSON objects to the server.
Basically I want to achieve the same behavior as this:
$.post(url, {"test": "test"}, function(response) {
console.log(response);
});
The fetch method is communicating with an web API which is unaccessable for me and expects a plain JSON object.
Normally I would just use FormData to pass data to the server, however the JSON will be transformed to a string [Object object]:
fetch(url, {
method: 'POST',
body: {"test": "test"}
})
.then(data => data.json())
.then(json => console.log(json))
.catch(e => console.error(e));
The body request seems to be empty when using $_POST (which is what the API is using), though gives the right value when using file_get_contents('php://input).
I though this had something to do with the wrong header given to the request. So I tried to add the header Ajax post uses: content-type:multipart/form-data;. However, this also did not get any value.
I was wondering if this was explicity intentional to not use plain JSON object to give as data, or that I'm simply missing something?
This does work, but is not allowed as it is a stringify version of the JSON object:
var formData = new FormData();
formData.append('data', JSON.stringify(data));
fetch(url, {
method: 'POST',
body: formData
})
.then(data => data.json())
.then(json => console.log(json))
.catch(e => console.error(e));
Let's say your data is inside a variable var data = { a: "some data", b: 123 }. If you want your code in PHP to access these fields this way:
$_POST["a"] == "some data";
$_POST["b"] == 123;
Then you need to send the data in the formData format this way:
var fdata = new FormData();
fdata.append('a', 'some data');
fdata.append('b', '123');
Now you can send that data and PHP will have access to separated fields a and b but notice b will be a string, not a number.
What if you want to send an array. Let's say { c: ['hello', 'world', '!'] }? You must follow PHP name conventions and add the same name multiple times:
var fdata = new FormData();
fdata.append('c[]', 'hello');
fdata.append('c[]', 'world');
fdata.append('c[]', '!');
After setting the form data instance, you can use it as the body of the request.
So firstly, I need to post to the POST-protocol, which is used by $_POST. I do this by adding a header of application/x-www-form-urlencoded (which is the protocol used by $_POST, as described in the docs) to the fetch post request:
fetch(url, {
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), // Default header which $_POST listens to
...
Now the way $.post actually sends data is by creating a serialized string (eg: a%5Bone%5D=1) of the given object. To transform an object to a serialized string, you can use $.param:
fetch(url, {
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), // Default header which $_POST listens to
method: 'POST',
body: $.param(data)
})
This will make you able to retreive data from $_POST like you would do with a simple $.post.
I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.