[Vuejs]-SOLVED how to send variable from symfony server to VITE VUE server

0👍

the problem is solved.
I put the code (8 files, so that you can see everything

first the VITE VUE project which is inside 1 folder INTO the Symfony project
The vite.config.ts file

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [vue()],
    server : {
        proxy: {
            "/api": {
                target: "https://127.0.0.1:8000",
                changeOrigin: true,
                secure: false,
                ws:true,
            },
        },
    },
})

here, in the proxy, we put the prefix to all symfony routes
And
we also fill in the address of the Symfony server with the port (127.0.0.1:8000)

index.ts file

import { createRouter, createWebHistory } from "vue-router";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/view01",
      name: "view01",
      component: () => import("../views/view01.vue"),

    },
    {
      path: "/view02",
      name: "view02",
      component: () => import("../views/view02.vue"),
    },
  ],
});

export default router;

This file is personal to VITE VUE, these are the routes of VITE VUE

main.ts file

import { createApp } from 'vue'

import App from './App.vue'
import router from "./router";

import './style.css'

const app = createApp(App);

app.use(router);

app.mount("#app");

personal to VITE VUE

the App.vue file. We start the ball of files.vue
these files in their basic form (the one I present here because I only know that for the moment)
are slitted into 3 pieces
the tags which represent what will be seen by the user in his browser
the tags which represent the "configuration" of the template tags. We organize the data, we indicate what we send to Symfony and what we receive from it
style tags= css

<script setup lang="ts">

import { RouterLink, RouterView } from "vue-router";
import { ref } from 'vue'

</script>

<template>
    <main>
        <section class="section01">
            <div class="nav">
                <div class="item">
                    <RouterLink to="/view01">Page01</RouterLink>
                </div>
                
                <div class="item">
                    <RouterLink to="/view02">Page02</RouterLink>
                </div>
            </div>

            <div class="contentView">
                <RouterView />
            </div>
        </section>
    </main>

</template>

<style scoped>

    .section01 {
      flex-direction: column;
      height: 100vh;
      width: 100%;
      margin-left: 0;
      align-items: flex-start;
    }

    .nav {
      background-color: #ddd;
      display: flex;
      justify-content: space-between;
      padding: 20px;
    }

    .item {
      text-align: center;
      margin-right: 20px;
    }

    .contentView {
      flex: 1;
      aspect-ratio: 16/9;
    }
</style>

strictly personal to VITE VUE, it is the links that lead to the different views

view01.vue file

<template>
  <main>
    <section class="section01">
      <!-- Affiche le json en brut -->
      <!-- {{ message }} -->
      <div class="name">
        name: {{ parsedMessage.name }}
      </div>
      <br>
      <div class="lastname">
        lastname: {{ parsedMessage.lastname }}
      </div>
    </section>
  </main>
</template>

<script setup lang="ts">

import { ref, computed } from "vue";

// la valeur de message a sa declaration
// est 1 string vide
const message = ref("");

// la valeur de parsedMessage a sa declaration
// est 1 json vide
const parsedMessage = ref ({});

// correspond à la route du controller SF
fetch("/api")
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    // contient le contenu du json,
    // utilisé uniquement pr verif de la bonne reception
    // ms pas utilisable en tant que tel
    message.value = JSON.stringify(data);

    // contient 1 sorte de tableau associatif
    // clé - valeur, dt on se servira
    // pr affichage ds le template
    parsedMessage.value = data;
  })
  .catch((error) => {
    console.log(error);
  });

</script>

<style scoped>
.section01 {
  background-color: blue;
  display: flex;
  flex-direction: column;
  aspect-ratio: 16/9;
  height: min(100vh, calc(16vw / 9));
  width: 100%;
  text-align: left;
}

.name {
  background-color: blue;
  width: 100%;
  text-align: left;
}

.lastname {
  background-color: blue;
  width: 100%;
  text-align: left;
}
</style>

view02.vue file

<template>
  <main>
    <section class="section01">
        
        You want to change your name?
        <br>
        ok, please enter your new name:
        <br>
        <br>
        <form @submit.prevent="submitForm">
            <label for="name">Name:</label>
            <input id="name" type="text" v-model="name" />
            <br>
            <br>
            <button type="submit">Submit</button>
        </form>
        <br>
        <br>
        Your new name will be:
        <br>
        name: {{ parsedResponse.value }}
        <br>
        message: {{ parsedResponse.message }}
    </section>
  </main>
</template>

<script setup lang="ts">

import { ref } from "vue";

const name = ref("");
const response = ref("");

// la valeur de parsedResponse a sa declaration
// est 1 json vide
const parsedResponse = ref ({});

function submitForm() {
    const obj = {
    value: name.value
  };
  fetch('https://localhost:8000/api/change/name', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(obj)
  })
  .then(response => {
    return response.json();
  })
  .then(data => {
      // symfonyResult.value = JSON.stringify(data);
      response.value = JSON.stringify(data);
      console.log("Form submitted with name:", name.value);
      

      parsedResponse.value = data;
  })
  .catch(error => {
    // handle error
    console.log(error)
  });
}

</script>

<style scoped>
.section01 {
  background-color: blue;
  display: flex;
  flex-direction: column;
  aspect-ratio: 16/9;
  height: min(100vh, calc(16vw / 9));
  width: 100%;
  text-align: left;
}

</style>

Symfony controllers

IndexController.php

<?php

    namespace App\Controller;

    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\Routing\Annotation\Route;

    class IndexController extends AbstractController
    {
        #[Route('/api', name: 'app_index')]
        public function index(): Response
        {
        
        $jsonObject = '{"name": "ZZZ", "lastname": "Doe"}';
        $response = new JsonResponse($jsonObject, 200, [], true);

        return $response;

        
           // return $this->render('index/index.html.twig', [
           //     'controller_name' => 'IndexController',
           // ]);
           //
           // return json_encode(['message'=> 'coucou']);
        }
    }

ChangenameController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

use Symfony\Component\HttpFoundation\JsonResponse;

class ChangeNameController extends AbstractController
{

    #[Route('/api/change/name', name: 'app_change_name')]
    public function index(Request $request): Response
    {

        $jsonObject = $request->getContent();
        $data = json_decode($jsonObject, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            $errorMsg = json_last_error_msg();
        }

        // traitement, on ajoute 1 paire clé/valeur au json
        // avt de le renvoyer
        $data['value'] = strtoupper($data['value']);
        $data['message'] = 'Data received successfully!';

        return new JsonResponse($data);

    }

    }

it’s in this file that it was causing the problem (in fact it was me who was causing the problem, because the code is functional)
in fact if you look at the first screen, with the FF console, we see that I am displaying the branch of the controller and so me I was trying to display this branch into FF.
it can’t work
1), I don’t have a render method
2), the controller, does 3 things
— it retrieves the information sent by the VITE VUE edge (the data entered by the user)
— he treats them
— it sends them back to the VITE VUE edge (the return)
3) structure
— symfony takes care of the back-end
— VITE VUE takes care of the front end,
there’s no point in calling the symfony branch

I pass in solved, I nevertheless have 1 question.
if I change my prefixes in VITE VUE and Symfony, i.e. if I remove the word "api", I get the error where Symfony cannot find a route
for 127.0.0.1:8000/view01.vue and 127.0.0.1:8000/view02.vue
Would you know the reason?

Translated with web engine, so i hope it will be okay
thank you for reading

Leave a comment