Как перенаправить на шаблон VUE с помощью Spring Rest Controller? - PullRequest
0 голосов

У меня есть этот контроллер REST для моего приложения на основе Vue. js:

@CrossOrigin(origins = ["*"], maxAge = 3600)
@RestController
@RequestMapping
class AuthController {

    @Autowired
    lateinit var authenticationManager: AuthenticationManager

    @Autowired
    lateinit var userRepository: UserRepository

    @Autowired
    lateinit var encoder: PasswordEncoder

    @Autowired
    lateinit var jwtProvider: JwtProvider

    @PostMapping("/login")
    fun authenticateUser(@Valid @RequestBody loginRequest: LoginUser): ResponseEntity<*> {

        val userCandidate: Optional<User> = userRepository.findByUsername(loginRequest.username!!)

        if (userCandidate.isPresent) {
            val user: User = userCandidate.get()
            val authentication = authenticationManager.authenticate(
                    UsernamePasswordAuthenticationToken(loginRequest.username, loginRequest.password))
            SecurityContextHolder.getContext().setAuthentication(authentication)
            val jwt: String = jwtProvider.generateJwtToken(user.username!!)
            val authorities: Set<GrantedAuthority> = user.roles!!.stream().map({ role -> SimpleGrantedAuthority(role.name) }).collect(Collectors.toSet<GrantedAuthority>())
            return ResponseEntity.ok(JwtResponse(jwt, user.username, authorities))
        } else {
            return ResponseEntity(ResponseMessage("User not found!"),
                    HttpStatus.BAD_REQUEST)
        }
    }
}

Вот моя страница Login.vue:

<template>
    <div div="login">
        <div class="login-form">
            <b-card
                    title="Login"
                    tag="article"
                    style="max-width: 20rem;"
                    class="mb-2"
            >
                <div>
                    <b-alert
                            :show="dismissCountDown"
                            dismissible
                            variant="danger"
                            @dismissed="dismissCountDown=0"
                            @dismiss-count-down="countDownChanged"
                    > {{ alertMessage }}
                    </b-alert>
                </div>
                <div>
                    <b-form-input type="text" placeholder="Username" v-model="username"/>
                    <div class="mt-2"></div>

                    <b-form-input type="password" placeholder="Password" v-model="password"/>
                    <div class="mt-2"></div>
                </div>

                <b-button v-on:click="login" variant="primary">Login</b-button>

                <hr class="my-4"/>

                <b-button variant="link">Forget password?</b-button>
            </b-card>
        </div>
    </div>
</template>

<script>
    import {AXIOS} from './http-common'

    export default {
        name: 'SignIn',
        data() {
            return {
                username: '',
                password: '',
                dismissSecs: 5,
                dismissCountDown: 0,
                alertMessage: 'Request error'
            }
        },
        methods: {
            login() {
                AXIOS.post(`/login`, {'username': this.$data.username, 'password': this.$data.password})
                    .then(response => {
                        this.$store.dispatch('login', {
                            'token': response.data.accessToken,
                            'roles': response.data.authorities,
                            'username': response.data.username
                        });
                        this.$router.push('/home')
                    }, error => {
                        this.$data.alertMessage = (error.response.data.message.length < 150) ? error.response.data.message : 'Request error. Please, report this error website owners';
                        console.log(error)
                    })
                    .catch(e => {
                        console.log(e);
                        this.showAlert();
                    })
            },
            countDownChanged(dismissCountDown) {
                this.dismissCountDown = dismissCountDown
            },
            showAlert() {
                this.dismissCountDown = this.dismissSecs
            }
        }
    }
</script>

<style>
    .login-form {
        margin-left: 38%;
        margin-top: 50px;
    }
</style>

Вот мои router.js настройки:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import SignIn from '@/components/SignIn'
import SignUp from '@/components/SignUp'
import Invites from '@/components/Invites'
import UserPage from '@/components/UserPage'

Vue.use(Router)

export default new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home
        },
        {
            path: '/home',
            name: 'Home',
            component: Home
        },
        {
            path: '/login',
            name: 'SignIn',
            component: SignIn
        },
        {
            path: '/registration',
            name: 'SignUp',
            component: SignUp
        },
        {
            path: '/user',
            name: 'UserPage',
            component: UserPage
        },
        {
            path: '/invites',
            name: 'Invites',
            component: Invites
        }
    ]
})

И вот мой App.vue основной модуль:

<template>
  <div id="app">
    <b-navbar style="width: 100%" type="dark" variant="dark">
      <b-navbar-brand id="nav-brand" href="#">Interval words repeating service</b-navbar-brand>
      <router-link to="/"><img height="30px" src="./assets/img/kotlin-logo.png" alt="Kotlin+Spring+Vue"/></router-link>
      <router-link to="/"><img height="30px" src="./assets/img/spring-boot-logo.png" alt="Kotlin+Spring+Vue"/></router-link>
      <router-link to="/"><img height="30px" src="./assets/img/vuejs-logo.png" alt="Kotlin+Spring+Vue"/></router-link>
      <router-link to="/home" class="nav-link text-light" v-if="this.$store.getters.isAuthenticated">Words for today</router-link>
      <router-link to="/vocabulary" class="nav-link text-light" v-if="this.$store.getters.isAuthenticated">My vocabulary</router-link>
      <router-link to="/trash" class="nav-link text-light" v-if="this.$store.getters.isAuthenticated">My trash</router-link>
      <router-link to="/invites" class="nav-link text-light" v-if="this.$store.getters.isAdmin">Add new invite</router-link>
      <router-link to="/registration" class="nav-link text-light" v-if="!this.$store.getters.isAuthenticated">Registration</router-link>
      <router-link to="/login" class="nav-link text-light" v-if="!this.$store.getters.isAuthenticated">Login</router-link>
      <a href="#" class="nav-link text-light" v-if="this.$store.getters.isAuthenticated" v-on:click="logout">Logout </a>
    </b-navbar>
    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app',
  methods: {
    logout() {
      this.$store.dispatch('logout');
      this.$router.push('/')
    }
  } 
}
</script>

<style>
</style>

Я могу увидеть свою страницу «входа в систему» ​​после перехода на localhost:8080/login. Но когда я обновляю страницу, я получаю сообщение об ошибке «метод get не поддерживается». Как это исправить и получить доступ к этой странице после отправки запроса "получить" на адрес "/ login"?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...