0

I have VueJS frontend and Django REST as a backend, while running the below code of Signup I am getting below error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/v1/users/. (Reason: CORS request did not succeed). Status code: (null).

I am using Djoser for authentication.

SignUp.vue code

    <template>
    <div class="container">
        <div class="column">
            <div class="column is-4 is-offset-4">
                <h1 class="title"> Signup </h1>

                <form @submit.prevent= "submitForm">
                    <div class="field">
                        <label>Email</label>
                        <div class="control">
                            <input type="email" name="email" class="input" v-model="username">
                        </div>
                    </div>

                    <div class="field">
                        <label>Password</label>
                        <div class="control">
                            <input type="password" name="password1" class="input" v-model="password1">
                        </div>
                    </div>

                    <div class="field">
                        <label>Repeat Password</label>
                        <div class="control">
                            <input type="password" name="password2" class="input" v-model="password2">
                        </div>
                    </div>
                    
                    <!-- showing error before submit buttton -->
                    <div class="notification is-danger" v-if="errors.length">
                        <p v-for="error in errors" v-bind:key= "error"> {{ error }} </p>
                    </div>

                    <div class="field">
                        <div class="control">
                            <button class="button is-success">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

</template>

<script>
import axios from 'axios'
import {toast} from 'bulma-toast'

export default {
    name: 'Signup',
    data() { // for v-modelin input tag
        return {
            username: '',
            password1: '',
            password2: '',
            errors: [] //we will push all the errors in this array
        }
    },
    methods: {
        async submitForm() {
            this.errors = []
            if (this.username == '') {
                this.errors.push('The username is missing!!')
            }

            if (this.password1 == '') {
                this.errors.push('Password is too short')
            }

            if (this.password2 != this.password1) {
                this.errors.push('Passwords are not matching')
            }

            //if no error(empty error array) we will send details to backend
            if  (!this.errors.length) {
                const FormData = {
                    username: this.username,
                    password: this.password1
                }
            }

            axios
                .post('/api/v1/users/', FormData) //calling backend api
                .then(response => { //rendering response
                    toast({
                        message: 'Account has been created, Please Login',
                        type: 'is-success',
                        dismissible: 'true',
                        pauseOnHover: 'true',
                        duration: 2000, //mili seconds
                        position: 'bottom-right',
                    })

                    this.$router.push('/login') //after successfull signup, route to Login
                })
                .catch(error => {
                    if (error.response) {
                        for (const property in error.response.data) {
                            this.errors.push(`${property}: ${error.response.data[property]}`)
                        }
                    } else if (error.message) {
                        this.errors.push('Something went wrong. Please try again!')
                    }
                })
            //console.log('submitForm')
            //console.log(this.username)
        }
    }
}
</script>

index.js(store folder)

import { createStore } from 'vuex'

export default createStore({
  state: {
    isLoading: false,
    isAuthenticated: false,
    token: ''
  },
  getters: {
  },
  mutations: {
    initializeStore(state) {
      if (localStorage.getItem('token')) {
        state.token = localStorage.getItem('token')
        state.isAuthenticated = true
      } else {
        state.token = ''
        state.isAuthenticated = false
      }
    },
    setIsLoading(state, status) {
      state.isLoading = status
    },
    setToken(state, token){
      state.token = token
      state.isAuthenticated = true
    },
    removeToken(state) { //for signout
      state.token = ''
      state.isAuthenticated = false
    }
  },
  actions: {
  },
  modules: {
  }
})

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

axios.defaults.baseURL = 'http://127.0.0.1:8000' //Dajngo rest url

createApp(App).use(store).use(router, axios).mount('#app')
Yashraj
  • 73
  • 1
  • 5
  • Not sure what problem you ahve: Connection error fpr a websocket connection? (where is the code for the websocket connection?). Or. error in an HTTP POST request? If yes, dies the request work tested with other tools? – Nechoj Apr 19 '22 at 11:11
  • I have added main.js file & index.js file to the question. Hope it helps you to understand question better. – Yashraj Apr 19 '22 at 12:21
  • Still, in your code there is no hint about a websocket connection to `ws://192.168.123.131:8081/ws`, and you did not answer the question whether the POST url works with other tools. Also, this topic might help for testing your code: https://stackoverflow.com/questions/5725430/http-test-server-accepting-get-post-requests – Nechoj Apr 19 '22 at 13:15
  • Ultimately this is my errror: xhr.js?1a5c:210 POST http://127.0.0.1:8000/api/v1/users/ 400 (Bad Request). Not sure from where this is coming: ws://192.168.123.131:8081/ws – Yashraj Apr 19 '22 at 13:37
  • You will need to find out what credentials / parameters a successful call to the url 127.0.0.1:8000/api/v1/users need. You will need to use another tool to send such a request to this url and then examine the headers and the payload. Then compare to the headers and payload of your call (using the web development tools). See also https://assertible.com/blog/7-http-methods-every-web-developer-should-know-and-how-to-test-them – Nechoj Apr 19 '22 at 16:12
  • After resolving it, I am getting new error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/v1/users/. (Reason: CORS request did not succeed). Status code: (null). – Yashraj Apr 20 '22 at 04:58
  • See here: https://stackoverflow.com/questions/50949594/axios-having-cors-issue and here https://stackoverflow.com/questions/35760943/how-can-i-enable-cors-on-django-rest-framework – Nechoj Apr 20 '22 at 05:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244038/discussion-between-yashraj-and-nechoj). – Yashraj Apr 20 '22 at 06:23

0 Answers0