1. 零散知识点三
    1. git踩坑
    2. html-webpack-plugin踩坑
    3. node的exports和module.exports
    4. cookie跨域问题
    5. JS正则表达式后行断言

零散知识点三

git踩坑

git add .不会加入空文件夹,需要在文件夹下加入一个空的无效文件。目前做法是加入.gitkeep

使用场景:类似react-cli的工具,需要制定一个项目模板,提前设置好项目结构,但是目录下并没有文件。

html-webpack-plugin踩坑

使用默认template参数时,会寻找./src/index.ejs作为模版(注意有后缀)

如果没有则创建一个默认空模版,即使存在./src/index.html

如果想自定义模板需要自行指定文件

node的exports和module.exports

他俩指向同一引用

直接修改exports或module.exports都会导致不相等

exports = function() {};
exports === module.exports  //false
// or
module.exports = function() {};
exports === module.exports  //false

模块化可以通过定义exports的属性去暴露

//module.js
exports.methods = function() {};  //正确

//index.js
const methods = require('module.js');

如果直接定义exports是无效的

//module.js
exports = function() {};  //无效

//index.js
const methods = require('module.js');

还可以通过定义module.exports或定义module.exports的属性去暴露,但是直接定义会造成上述的不相等情况

//module.js
module.exports = function() {};  //正确

//or

module.exports.methods = function() {};  //正确

//index.js
const methods = require('module.js');

cookie跨域问题

前端:需要将请求头的withCredentials设置true,前端就只需要做这点

后端:需要设置两个请求头,第一个是请求头Access-Control-Allow-Origin置为唯一域,不可以是范围性的比如*;第二个是Access-Control-Allow-Credentials置为true

踩坑:express模板使用res.cookies API的时候需要安装“cookie-parser”,否则无法获得,但是可以通过req.headers.cookie去获取cookie字段,代码如下

//ajax
axios({
    method: 'POST',
    url: 'http://localhost:3000/cors',
    withCredentials: true
}).then((res) => {
    console.log(res.data);
});
//node
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
app.use(cookieParser());

app.post('/cors', function (req, res) {
    res.set({
        'Access-Control-Allow-Origin': 'http://localhost:5500',
        'Access-Control-Allow-Credentials': true
      });
    res.cookie('rememberme', '1', {
        expires: new Date(Date.now() + 900000)
    });
    console.log(req.cookies.rememberme);
    res.send({
        a: '1'
    });
}).listen(3000);

JS正则表达式后行断言

JS直到ES6才开始支持后行断言,在node v8.9.4以下的版本使用后行断言都会报错,所以想要在node中使用后行断言尽量使用最新版本node

用途:捕获

比如:ab

  • 捕获a后的b,在正则表达式的意义上为b的前一个位置是a,属于后行断言。

    const reg=/(?<=a)b/    //b
  • 捕获b前的a,在正则表达式的意义上为a的后一个位置是b,属于先行断言。

    const reg=/a(?=b)/     //a