Twilio.js:264 Uncaught TypeError: url.URL is not a constructor

Twilio.js:264 Uncaught TypeError: url.URL is not a constructor

Twilio.js:264 Uncaught TypeError: url.URL is not a constructor

为什么我在使用 twilio 短信 api 在 React js 中发送短信时收到此类错误

这是我的代码

const accountSid = "ACa7e54c4******391cc08f61bd";
const authToken = "0ab3a929*****c4be9466b6878";
const client = require('twilio')(accountSid, authToken);

const send_sms = (type)=>{
    client.messages
      .create({from: '+19547***', body: 'body', to: '+917828***4'})
      .then(message => console.log(message.sid));
} 

此处为 Twilio 开发人员布道师。

Twilio Node module 不能在浏览器中使用,将无法工作。这是有意为之,因为您不应直接从客户端应用程序调用 Twilio API。

为了从客户端调用 Twilio API,您需要嵌入您的帐户 SID 和授权令牌,正如我在您的示例中看到的那样。当您这样做时,您会将您的凭据暴露给任何使用您的应用程序的人,而恶意用户可能会提取您的凭据并滥用您的帐户。

您不应从客户端向 API 发出请求,而应通过您自己的服务器代理它们。好消息是我有一个博客 post,你可以关注它,它会引导你 how to send an SMS from React with Twilio 详细解释这一点。

It's pretty much well I got my silly mistake and here's my code working well I hope It's right way to so, I'm running my react js server on 3000 port and express server on 4000 so yeah it working well ..

//index.js for express server 

const express = require('express'); 
const cors = require('cors');
const twilio = require('twilio'); 

//twilio requirements -- Texting API 
const accountSid = 'ACa7********************1bd';
const authToken = '0ab*****************6b6878'; 
const client = new twilio(accountSid, authToken);

const app = express(); 
app.use(cors()); 

app.get('/api', (req, res) => {
    res.send('Server Running')
})

app.post('/api/send-sms', (req, res) => {
    res.send('Hello to the Twilio Server')
    const {  msg } = req.query;
    client.messages.create({
        body: "Hello mesage from twilio ..",
        to: "+917******784",  
        from: '+19*******13'
    }).then((message) => console.log(message.body));
})
app.listen(4000, () => console.log("Running on Port 4000"))

And here's the function which get triggered on onClick event

const send_sms = (type)=>{

    fetch('http://localhost:4000/api/send-sms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(msg)
    })
    .then(res => res.json())
    .then(data => {
        console.log(data);
    })

}

I just wana welcome if correction is needed please let me know because it display only one red alert Uncaught (in promise) SyntaxError: Unexpected token H in JSON at position 0

enter image description here

let me just know what I'm missing or needed a correction.