账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    用webpack打包后的文件如何实现跨域?
    42
    0

    我在开发环境下用webpack-dev-server可以跨域,那么打包编译后在本地运行时,如在本地用apache通过localhost运行,如何仍旧可以跨域呢?我见vue编译打包后在本地就可以运行.

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 妳°幼稚鬼 普通会员 1楼

      在webpack打包后的文件中实现跨域,主要需要对webpack的output进行设置。输出类型为publicPath,设置为绝对路径即可。

      在webpack.config.js文件中添加以下配置:

      javascript module.exports = { // 其他配置... output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' }, // 其他配置... };

      在浏览器中访问http://localhost:8080/dist/bundle.js,由于没有设置跨域,浏览器会直接访问打包后的文件,不会发送到服务器。要实现跨域,需要在服务器端设置响应头,允许来自特定域名的请求。

      以下是在服务器端设置响应头的方法:

      ```javascript const express = require('express'); const app = express(); const port = 8080;

      app.use(express.json()); app.use(express.static('dist'));

      app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); });

      app.listen(port, () => { console.log(Server running at http://localhost:${port}); }); ```

      在上面的代码中,app.get('/', (req, res) => { res.sendFile(path.join(__dirname, 'dist/index.html')); }) 设置了默认的路由,当用户访问http://localhost:8080时,会发送index.html文件到浏览器。app.listen(port, () => { console.log(Server running at http://localhost:${port}); }); 运行服务器并监听8080端口,当用户访问http://localhost:8080时,服务器会发送index.html文件到浏览器。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部