• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

devServer 관련하여 질문이 있습니다. (수정)

21.04.26 18:11 작성 조회수 264

1

안녕하세요.

webpack 강의를 모두 수강하고 프로젝트에 적용하던 중 몇 가지 의문점이 생겨 질문 드립니다.

1️⃣ devServer 시작시 이유없이 요청이 발생합니다.

아래는 webpack.config.js 설정입니다.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
require('dotenv').config();

module.exports = {
  mode: 'none',
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname'dist'),
  },
  devServer: {
    port: 9000,
    proxy: {
      '/api': {
        target: 'https://newsapi.org/v2',
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: { '^/api''' },
      },
   },
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'index.html',
    }),
    new webpack.DefinePlugin({
      'process.env': {
        API_KEY: JSON.stringify(process.env.API_KEY),
      },
    }),
  ],
};

앞에서 예제로 사용한 코드에 추가적으로 .env를 사용하기 위해 dotenv 라이브러리를 설치하여 적용하였습니다.

그런데 server 실행 후, 개발자 도구를 열어보면 아래와 같은 오류가 발생합니다.

제 코드 어딘가에 잘 못 입력한 부분이 있어서 그런걸까요? (index.html은 webpack.config.js와 같은 레벨에 있습니다.)

2️⃣ proxy가 동작하지 않습니다.

News API를 통해 뉴스 데이터를 받아오려 했는데 CORS 문제가 발생하여 webpack devServer에 proxy 설정을 하였습니다. 제 생각으론 request url중 '/api/...'가 포함되는 요청들에대해 '/api'''으로 그리고 앞에 target으로 지정한 'https://newsapi.org/v2'가 붙어서 request 될거라 예상했습니다.

그런데 제 예상과 달리 여전히 'http://localhost:9000/api/top-headlines...'으로 요청하고 있었고 debug를 출력해보니 아래처럼 나왔습니다.

[HPM] Rewriting path from "/api/top-headlines?country=kr&apiKey=93e..." to "/top-headlines?country=kr&apiKey=93e..."

[HPM] GET /api/top-headlines?country=kr&apiKey=93e694811aac419db735d29a23b26c57 ~> https://newsapi.org/v2

Vue CLI로 webpack.confing를 셋팅 했을 때는 이런 문제가 발생하지 않았는데 직접 구현하려하니 원인을 잘 모르겠습니다. 😥

아이디어나 조언 주시면 감사하겠습니다.

답변 2

·

답변을 작성해보세요.

1

vineetprasad님의 프로필

vineetprasad

2024.02.21

  1. Regarding the unexpected requests occurring when starting devServer, your setup appears correct. However, the error you're encountering might stem from an issue with the configuration or environment setup. Make sure your .env file containing your API_KEY is correctly configured and accessible. Also, ensure that the index.html file is indeed at the same level as your webpack.config.js file. Sometimes, small discrepancies can cause such errors.

2. As for the proxy not functioning as expected, it's a bit perplexing that the '/api' prefix is still present in your requests despite the proxy configuration. Your assumption about how the proxy should work seems accurate. However, there might be an oversight in the configuration or how requests are made.

Regarding your News API integration, have you considered using newsdata.io? It provides a seamless integration for accessing news data without CORS issues. Integrating it into your webpack configuration might streamline your development process and alleviate the CORS-related challenges with the News API.

I hope these suggestions help! Feel free to provide more details if you need further assistance troubleshooting the issues you're encountering.

0

안녕하세요 taylous님, 답변 드릴게요 :)

1. 웹팩 데브 서버를 실행할 때 index.js의 위치를 찾질 못하는 것 같습니다. 지정하신 entry의 상대 경로가 맞는지 확인해 보시면 될 것 같아요.

2. 첨부해주신 News API는 저도 사용해보질 않아서 자세한 답변이 어려울 것 같습니다. 사이트 잠깐 살펴보니 API Key를 발급받아 사용하는 걸로 봐서는 CORS 필터를 따로 설정하지 않으셔도 될 것 같은데 이 부분 역시 강의에서 다루는 내용이 아닌 개인 프로젝트와 관련된 질문이라 자세한 답변이 어려울 것 같습니다. 참고하실 만한 자료들 안내드릴테니 확인해 보시면 좋을 것 같아요 :)

웹팩 프록시 설정

웹팩 프록시 문서