1

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?

enter image description here

2

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.

1
  • CSRF protection is disabled, still I'm getting an error. Also I use headless Craft together with decoupled frontend on Nuxt.js, so I need a way to fetch data with axios on Nuxt.js without using a twig template code. – Oleksandr Staniev Dec 15 '20 at 11:51
2

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.

1

After enabling the headless mode in Craft I'm getting the same error in JSON format:

enter image description here

Anyway I guess I have to write some module for that extra functionality. Thank you for the tips!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.