在本地使用节点API测试MySQL数据库

时间:2018-11-04 18:34:36

标签: mysql node.js ssl

我创建了一个简单的MySQL数据库,并使用XAMP将其托管在本地计算机上。 然后,我使用node创建一个api并表达js。使用Postman进行测试似乎一切正常,但是,如果我尝试从外部应用程序使用API​​,则会收到与SSL证书相关的错误。遵循有关Medium的教程之后,我设法使错误消失了,但是仍然无法测试api,但我始终会遇到以下错误:

  

无法加载资源:net :: ERR_CONNECTION_CLOSED

     

app.js:18请求失败TypeError:无法获取

这是我的api

const express = require('express')
const app = express()
const fs = require('fs')
const https = require('https');
const bodyParser = require('body-parser');
const mysql = require('mysql');

//local host port
const port = 8080;


//read the certificate
const httpsOptions = {
  key: fs.readFileSync('../security/test-privatekey.pem'),
  cert: fs.readFileSync('../security/my-certificate.pem')
}

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

//databse info
var db = mysql.createConnection({
  host:'localhost',
  user:'admin',
  password:'password',
  database:'tutorial'
});

//connect to the database
db.connect((err) => {
  if(err){
    console.log('error',);
    throw err;
  }
  console.log('database working');
})

app.get('/', (req, res)=>{
  res.send('running database');
});


//get students
app.get('/api/getstudent', (req, responce)=> {
  const sql = 'SELECT * FROM `students` ORDER BY `students`.`name` ASC';

  db.query(sql, (err, res)=> {
    if (err) throw err;

    const str = JSON.stringify(res);

    responce.send('retuning data' + str);
  });
});

//insert student
app.post('/api/inserstudent', (req, responce)=> {
  const sql = "INSERT INTO students (name, age) VALUES ('test-student', 15)";

  db.query(sql, (err, res)=> {
    if (err) throw err;
    console.log('inserted');
    responce.send('retuning data');
  });
});


https.createServer(httpsOptions, app)
  .listen(port, () => {
      console.log('server running at ' + port)
  })

这就是我发出请求的方式

init = () =>{
  const req = 'https://localhost:8080/api/getstudent';
  fetch(req)
    .then(function(response) {
      console.log(response); 
    }).catch(function(error) {  
      console.log('Request failed', error)  
    });
}

这是我导航到api网址时chrome显示页面的方式

enter image description here

0 个答案:

没有答案