Programing

다른 포트에서 실행 중인 Vue 애플리케이션에서 노드 익스프레스 서버 API 호출

c10106 2022. 3. 9. 09:52
반응형

다른 포트에서 실행 중인 Vue 애플리케이션에서 노드 익스프레스 서버 API 호출

나는 최근에 vue.js를 배우기 시작했고 현재 vue-simple-webpack 템플릿, 익스프레스, mongo와 함께 vue.js를 사용하여 간단한 애플리케이션을 개발하고 테스트하고 있다.

애플리케이션 프런트엔드는 포트 8080에서 실행되며 서버는 다른 포트(3000)에서 실행 중임

여기 내 것이 있다.server.js여기서 데이터를 얻을 수 있는 간단한 api가 있다.localdb

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const mongodb = require('mongodb');
const bodyParser= require('body-parser');
const app = express();
var db;

var URL='mongodb://localhost:27017/'+'mydb';
console.log(URL);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

MongoClient.connect(URL, (err, database) => {
  if (err) 
    return console.log(err);
  db = database;
  app.listen(3000, () => {
    console.log('listening on 3000');
  })
})

app.get('/products', (req, res) => {
    db.collection('products').find().toArray(function(err, results) {
    console.log(results)
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(results));
    })
})

server.js를 시험해보니 효과가 있었다. 아래 스크린샷을 보라.

여기에 이미지 설명을 입력하십시오.

Vue 애플리케이션이 실행 중임http://localhost:8080/웹 팩 템플릿의 기본 구성 사용.나는 전화를 하려고 한다./products$s를 사용하는 vue.js 파일에서 api end는 다음과 같이 얻는다...

export default {
  name: 'Products',
  methods: {
        get: function() {
            // GET request
            this.$http({
                url: '/products',
                method: 'GET'
            }).then(function(response) {
                console.log('ok');
            }, function(response) {
                console.log('failed');
            });
        }
    }
}

그러나 나는 브라우저 콘솔에서 다음과 같은 오류를 얻는다.

여기에 이미지 설명을 입력하십시오.

보시다시피, 비록 내가 항구를 사용하고 있지만3000server.js, 내가 접속을 시도할 때/productsapi end, 실제로 포트를 통과한다.8080그러므로 그것은 404 http 에러를 던진다.

내 질문은 다른 포트에서 실행되는 프런트엔드 내에서 API 엔드에 어떻게 접근할 수 있는가 하는 것이다.그게 가능하긴 해?

나는 여기서 API Proxying을 사용할 수 있는가? 만약 그렇다면, 웹에 많은 정보가 없기 때문에 누군가가 나에게 그것을 어떻게 하는지 올바른 방향을 가리켜줄 수 있는가?

웹 팩에서 제공하는 프록시 구성을 사용할 수 있다.

문서: https://webpack.js.org/configuration/dev-server/#devserver-properties

코드 조각 구성:

proxy: {
  "/products": "http://localhost:3000/products"
}

더 나은 방법은 /api/* 요청을 http:///host:port/api/* URL로 전달하는 것이다.

참조URL: https://stackoverflow.com/questions/46792214/calling-node-express-server-api-from-vue-application-running-in-a-different-port

반응형