Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node ES6语法引入无法正常使用,ES5语法才可以使用 #32

Open
Dr-SummerFlower opened this issue Nov 23, 2023 · 2 comments
Open

Comments

@Dr-SummerFlower
Copy link

使用作者提供的ES6 import导入无法正常使用,报错为:

TypeError: IP2Region is not a constructor
    at file:///C:/Users/17218/Desktop/getip/app.js:17:23
    at Layer.handle [as handle_request] (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\17218\Desktop\getip\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\index.js:280:10)
    at expressInit (C:\Users\17218\Desktop\getip\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\Users\17218\Desktop\getip\node_modules\express\lib\router\layer.js:95:5)

代码是这样的

import express from 'express';
import IP2Region from 'ip2region';

const app = express();

app.get('/', (req, res) => {
    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    if (ip.includes('::ffff:')){
        ip = ip.split('::ffff:')[1];
    }
    const ip2Region = new IP2Region();
    const ipAdress = ip2Region.search(ip)
    res.send({ip,ipAdress});
});

app.listen(3000, () => {
    console.log('http://localhost:3000');
})
@Dr-SummerFlower
Copy link
Author

研究出解决方法了,需要多加一句

import ip2region from 'ip2region';
const IP2Region = ip2region.default;
const query = new IP2Region();
const ipAddress = query.search(ip);

然后就正常了
本人学艺不精,能解释一下原因吗

@yourtion
Copy link
Owner

因为我在代码是通过 export default 的方式导出,但是又是通过 ts 编译成了 commonjs,所以用的时候就需要加 default。后续我可以优化一下。

https://remarkablemark.org/blog/2020/05/05/typescript-export-commonjs-es6-modules/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants