Craft CMS Asked on January 14, 2021
I need to fetch a list countries available for shipping in Craft Commerce.
The problem is that I use decoupled frontend on Nuxt.js and I need fetch it with Ajax call and not with the twig code.
I tried to call it in a Postman but it returns me a 403 – Forbidden error with message "User is not permitted to perform this action".
I couldn’t find something about the way of making request through Ajax in Commerce documentation, can you please tell me what I’m doing wrong here?
You need to provide a CSRF token, alternatively turn it off in your config/general.php file.
Set a token in your twig template:
{% set csrfToken = {
csrfTokenName: craft.app.config.general.csrfTokenName,
csrfTokenValue: craft.app.request.csrfToken,
} %}
<script type="text/javascript">
window.Craft = {{ csrfToken|json_encode|raw }};
</script>
Then include the CSRF token name and value in your post array (data):
data[window.Craft.csrfTokenName] = window.Craft.csrfTokenValue;
Alternatively you can set enableCsrfProtection to false in your general config file.
Answered by Syversen on January 14, 2021
The controller action you are hitting returns a template and I think that it is why you are getting this error.
If you don't have headlessMode
on (docs) you could make a quick template, add:
{% header "Content-Type: application/json"%}
{{ craft.commerce.countries.getAllCountries() | json_encode() | raw }}
Which would give you an endpoint you can then reach from your front end.
Alternatively, you could make a small module/plugin with a controller.
Answered by Oli on January 14, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP