npm run build生成vue项目放在服务器上无法调用API

AlloyTeamZy
  • 334

在执行npm run build之前,npm run dev在localhost时,项目可正常调用API,执行npm run build打包成dist之后,放在服务器上就无法调用API,老是报404错误。

本地:

clipboard.png

数据能存进数据库:

clipboard.png

服务器上:

clipboard.png

这是我的项目目录:

clipboard.png

附上关键文件代码:
server/api/userApi.js

    var models = require('../db');
    var express = require('express');
    var router = express.Router();
    var mysql = require('mysql');
    var $sql = require('../sqlMap');
    
    // 连接数据库
    var conn = mysql.createConnection(models.mysql);
    
    conn.connect();
    var jsonWrite = function(res, ret) {
        if (typeof ret === 'undefined') {
            res.json({
                code: '1',
                msg: '操作失败'
            });
        } else {
            res.json(ret);
        }
    };
    
    // 增加用户接口
    router.post('/addUser', (req, res) => {
        var sql = $sql.user.add;
        var params = req.body;
        console.log(params);
        conn.query(sql, [params.username, params.age], function(err, result) {
            if (err) {
                console.log(err);
            }
            if (result) {
                jsonWrite(res, result);
            }
        })
    });

module.exports = router;

server/db.js (能连上数据库,信息无误,内容忽略)

module.exports = {
    mysql: {
        host: '.....',
        user: '.....',
        password: '.....',
        database: '.....',
        port: '3306'
    }
}

server/index.js

const userApi = require('./api/userApi');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

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

// 后端api路由
app.use('/api/user', userApi);

// 监听端口
app.listen(3000);
console.log('success listen at port:3000......');

server/aqlMap

// sql语句
var sqlMap = {
    // 用户
    user: {
        add: 'insert into user_info(user_name, user_pwd) values (?,?)'
    }
}

module.exports = sqlMap;

显示组件:src/App.vue

<template>
  <div class="hello">
    <h1/>{{ msg }}</h1>
    <form>
      <input type="text" name="username" v-model="userName"> <br>
      <input type="text" name="age" v-model="age"> <br>
      <a href="javascript:;" @click="addUser">提交</a>
    </form>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      userName: '',
      age: ''
    }
  },
  methods: {
    addUser() {
      var name = this.userName;
      var age = this.age;
      this.$http.post('api/user/addUser', {
        username: name,
        age: age
      },{}).then((response) => {
        console.log(response);
      })
    }
  }
}
</script>

config/index.js

   // see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

module.exports = {
    build: {
        env: require('./prod.env'),
        index: path.resolve(__dirname, '../dist/index.html'),
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        productionSourceMap: true,
        // Gzip off by default as many popular static hosts such as
        // Surge or Netlify already gzip all static assets for you.
        // Before setting to `true`, make sure to:
        // npm install --save-dev compression-webpack-plugin
        productionGzip: false,
        productionGzipExtensions: ['js', 'css']
    },
    dev: {
        env: require('./dev.env'),
        port: 80,
        assetsSubDirectory: 'static',
        assetsPublicPath: './',
        proxyTable: {
            '/api': {
                target: 'http://localhost:3000/api/',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },
        // CSS Sourcemaps off by default because relative paths are "buggy"
        // with this option, according to the CSS-Loader README
        // (https://github.com/webpack/css-loader#sourcemaps)
        // In our experience, they generally work as expected,
        // just be aware of this issue when enabling this option.
        cssSourceMap: false
    }
}
回复
阅读 4.1k
1 个回答

这不是废话吗 ?? 你app.listen是在3000端口的 前端80端口怎么访问?? 你本地可以访问是因为下面这个把80端口转发到了3000端口 线上要访问的话也要做一个转发 用nginx或者apache都可以

dev: {
        env: require('./dev.env'),
        port: 80,
        proxyTable: {
            '/api': {
                target: 'http://localhost:3000/api/',
            }
        }
宣传栏