код: 403, сообщение: «Запрещено», ответ: при нажатии кнопки формы саммита - PullRequest
0 голосов
/ 18 апреля 2020

, когда я запускаю бэкэнд nodeJS, он работает нормально, а затем при вводе данных формы и отправке происходит ошибка.

На самом деле я пытаюсь отправить письмо с помощью ключа API SendGrid из страница контактов. Я не могу понять, какая ошибка приходит.

Дайте мне знать фактическую ошибку, с которой я сталкиваюсь. Это будет очень полезно для решения.

this is the error showing

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
error:  ResponseError: Forbidden
    at C:\Users\Rajesh\React works\hephywebAPI-1\node_modules\@sendgrid\client\src\classes\client.js:105:29
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: 403,
  message: 'Forbidden',
  response: {
    headers: {
      server: 'nginx',
      date: 'Fri, 17 Apr 2020 22:55:07 GMT',
      'content-type': 'application/json',
      'content-length': '281',
      connection: 'close',
      'access-control-allow-origin': 'https://sendgrid.api-docs.io',
      'access-control-allow-methods': 'POST',
      'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
      'access-control-max-age': '600',
      'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html'
    },
    body: { errors: [Array] }
  }
}

(FrontEnd) Контакт. js

handlchange = (event => {
        console.log(event);
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({ [name]: value })
    })
    handleSubmit = (event) => {
        event.preventDefault();

        this.setState({
            disabled: true
        });
        Axios.post('http://localhost:3040/api/email', this.state)
              .then( res => {
                  if(res.data.success) {
                      this.setState({
                          disabled: false,
                          emailSent: true
                      });

                  }
                  else{
                      this.setState({
                          disabled: false,
                          emailSent: false
                      });
                  }

              }
              )
              .catch(err => {
                  this.setState({
                      disabled: false,
                      emailSent: false
                  })
              })
    }

    render() {
        return (
            <div className="myfont">
                {/*<Homepart1 title={this.props.title} />*/}
                <Content>
                    <div style={{ textAlign: "center", paddingBottom: 50 }}>
                        <h3 style={{color:'red'}}> Let's Talk</h3>

                    </div>
                    <div  style={{ justifyContent: "center", alignItems: "center", display: "flex", }}>
                        <Form onSubmit={this.handleSubmit} style={{ width: 500 }}>
                            <Form.Group controlId="fullname">
                                <Form.Label>Full name</Form.Label>
                                <Form.Control type="text" placeholder="Enter name" name="name" id="full-name" value={this.state.name} onChange={this.handlchange} />
                                <Form.Text className="text-muted">
                                    We'll never share your email with anyone else.
                            </Form.Text>
                            </Form.Group>
                            <Form.Group controlId="email">
                                <Form.Label>E-mail</Form.Label>
                                <Form.Control type="email" placeholder="Enter email" name="email" id="email" value={this.state.email} onChange={this.handlchange} />
                                <Form.Text className="text-muted">
                                    We'll never share your email with anyone else.
                            </Form.Text>
                            </Form.Group>
                            <Form.Group controlId="message">
                                <Form.Label>Message</Form.Label>
                                <Form.Control as="textarea" placeholder="Write message" name="message" id="message" rows="3" value={this.state.message} onChange={this.handlchange} />
                                <Form.Text className="text-muted">
                                    We'll never share your email with anyone else.
                            </Form.Text>
                            </Form.Group>
                            <Button variant="info" className="mb-2" size="sm" type="submit" value={this.state.disabled}>Sent</Button>
                            {this.state.emailsent === true && <p className="d-inline success-msg">E-mail Sent</p>}
                            {this.state.emailsent === false && <p className="d-inline err-msg">E-mail not Sent</p>}
                        </Form>
                    </div>
                </Content>
            </div >
        )
    }
}
export default Contact;

( Backend) приложение. js

const express = require('express');
const bodyParser = require('body-Parser');
const cors = require('cors');
const sendGrid = require('@sendgrid/mail');

const app = express();

app.use(bodyParser.json());
app.use(cors());
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');

    res.setHeader('Access-Control-Allow-Methods', 'GET  , POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next(); 
}
);

app.get('/api', (req, res, next)=> {
    res.send('API status: Mama papa the great so what can I do for them')
}) 

app.post('/api/email', (req, res, next) => {
  sendGrid.setApiKey('xxxxxxxxxxxxxxxxxxxx');
   const msg = {
     to : 'my@gmail.com',
     from : req.body.email,
     Subject : 'My company Contact',
     text : req.body.message
   }

   sendGrid.send(msg) 
       .then(result => {
         res.status(200).json({
           success: true
         })
       })
       .catch(err => {
         console.log('error: ', err );
         res.status(401).json({
           success: false
         })
       })


});

app.listen(3040, '0.0.0.0');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...