Ajax и Vue cli - PullRequest
       1

Ajax и Vue cli

0 голосов
/ 12 февраля 2020

У меня есть vue cli проект, и я пытаюсь сделать ajax вызов в моем приложении, и он работает, если я go на localhost: 7999, но я хочу, чтобы он работал на та же страница, что и мое приложение, которое находится на localhost: 8080. я слышал об Ax ios, но, может быть, если есть способ без использования Ax ios, я надеюсь, что смогу найти его здесь.

vue .config. js

global.changement = "Johnny Depp";

var express = require('express')
var session = require('express-session')
var app = express();
var bodyParser = require('body-parser');

var userStoredInMemory = "LEBROONNN JAMES";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

app.get('/api/user', function (req, res) {
  res.json(changement);
});

app.post('/api/user', function (req, res) {
  // userStoredInMemory = req.body;
  // userStoredInMemory = "oui";
  res.send('User was already stored from express.');
});

app.listen(7999, function () {
  console.log('server up and running at 8080 port');
});

index. html

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
 
<script>
  
    function lebron() {
        $(document).ready(function () {
            $.ajax({
                type: 'GET',
                url: 'http://localhost:7999/api/user'
            })
            .done(function (data) {
                alert(JSON.stringify(data));
                localStorage.setItem('name',JSON.stringify(data));
            });
        });
    }

    setInterval(lebron, 1000);

</script>

<noscript>
    <strong>We're sorry but it doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
    
<div id="app"></div>
<!-- built files will be auto injected -->
 

нет вывода, оповещение не сделано.

1 Ответ

0 голосов
/ 16 марта 2020

Вам, вероятно, следует использовать cors на вашем сервере.

const express = require('express');
const cors = require('cors');
const app = express();

app.use((req, res, next) => cors({
        origin: 'localhost:8080', // your frontend app url
        optionsSuccessStatus: 200,
        credentials: true
    })(req, res, next)
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...