C++ 后端,Vue前端

发布于:2024-06-21 ⋅ 阅读:(140) ⋅ 点赞:(0)

参考2篇博客
1-VUE、C++前后端调用
2-Vue解决CORS header ‘Access-Control-Allow-Origin’ missing及同源、跨域问题

这里给出App.vue代码

<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'

import axios from 'axios'
import { ref } from 'vue'

const backendResponse = ref("bbbb")

const callBackend = () => {
      axios.get('http://localhost:8080/api/hello')
        .then(function(response){
          console.log("check msg");
          console.log(response.data);
          backendResponse.value = response.data
        })
        .catch(error => {
          console.error(error);
        });
      }
</script>

<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue" />

  <div class="hello">
    <button @click="callBackend">Call Backend</button>
    <p v-if="backendResponse">{{ backendResponse }}</p>
  </div>

</template>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

这里给出服务端代码

#include "mainwindow.h"
#include "httplib.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    //QApplication a(argc, argv);
    //MainWindow w;
    //w.show();
    //return a.exec();

    std::cout << "server start at http://localhost/8080" << std::endl;

    httplib::Server svr;

    svr.set_default_headers({
        { "Access-Control-Allow-Origin" , "*" },
        { "Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"},
        { "Access-Control-Max-Age", "3600"},
        { "Access-Control-Allow-Headers", "*"},
        { "Content-Type", "application/json;charset=utf-8"}
        });

    svr.Options("/api/hello", [](const httplib::Request& ,httplib::Response& resp) {
        std::cout << "OPTIONS ACCESS" << std::endl;
        resp.status = 200;
        });

    svr.Get("/api/hello", [](const httplib::Request& req, httplib::Response& res) {
      res.set_content("Hello from C++ backend!", "text/plain");
    });

    svr.listen("localhost", 8080);

}




网站公告

今日签到

点亮在社区的每一天
去签到