文章90
标签1
分类38

nodejs get请求axios

const axios = require("axios")
//axios.get("网站")
axios.get("https://www.baidu.com/")
.then(function(response){
    console.log(response.data);//使用函数function获取返回服务器请求数据,获取data数据,response可以缩写res
    //另外一种简化res=>{}
}).catch(error=>{
    console.log(error);//捕获错误
})

//带参数请求 - 关键字params
//格式
// params:{
//     word1:"",
//     .....
// }
//axios.get("url",{paramms:{
// id:"",
// name:""
// }})
axios.get("https://www.baidu.com/",{
    paramas:{
        Item_ID:1000,
    }
}).then(res=>{
    console.log(res.data);
}).catch(error=>{
    console.log(error);
})



//Post请求将get换成post axios.post


Node.js-读取文件,追加数据

1:

const fs = require('fs')

2

追加数据

fs.appendFileSync('xxx.txt','追加的数据内容', function (err) {

 if (err) throw err;
 console.log('视频+1');

});

3

判断文件是否为空

const stats = fs.statSync('xxx.txt')
if (stats.size === 0) {
//空

} else {
//不空

}

4

随机取文件某一排数据

// 读取文件内容,将每一行存储到数组中

    const contents = fs.readFileSync('videoid.txt', 'utf8').split('\n')

// 随机选择一行并输出到控制台

    const randomIndex = Math.floor(Math.random() * contents.length)
    console.log(contents[randomIndex])

调用js文件里面的函数

1.文件1:test1.js

function name(){

console.log("您好");

}
module.exports={name}

2.文件2:test2.js

//引入文件.
const thisname=require("./test1")
//直接用.
thisname.name();

输出 您好

Node.js连接数据库(创建连接池不断开)!

#1:安装模块
npm install mysql -g
#引用sql

const mysql=require('mysql');
#2:创造连接池

const pool = mysql.createPool(
{
connectionLimit: 20,
host: '*****',
port: ***,
user: '***',
password: '***',
database: '***'//需要操作的数据库名称
})

#3:开始连接
pool.getConnection((err, connection) => {
    if (err) throw err

    console.log('连接成功!')

    connection.release()
})

#数据库记得开权限允许连接的IP

QQ图片20230426164538.png

">