How to send a post request to mailchimp on express through react

∥☆過路亽.° 提交于 2021-02-11 07:21:55

问题


I am trying to send a new membership from a form in react to my express server to add to the mailchimp memberlist I am getting a cors error and I don't know if I am missing any proxys. I want a user to be able to sign up in react and then it sends it to the mailchimp database

I have been able to get the members list but I am not allowed to post to it :

This is my express backend :

const express = require('express');
const Mailchimp = require('mailchimp-api-v3');
require('dotenv').config();

var request = require('superagent');
var mc_api_key = process.env.REACT_APP_MAILCHIMP_API;
var list_id = process.env.REACT_APP_LIST_ID;

const app = express();

const mailchimp = new Mailchimp(mc_api_key);
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

app.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Content-Type");
next();
});

// Routes
app.post('/signup', function (req, res) {
request
    .post('https://' + 'us20' + '.api.mailchimp.com/3.0/lists/' + list_id + '/members/')
    .set('Content-Type', 'application/json;charset=utf-8')
    .set('Authorization', 'Basic ' + new Buffer('any:' + mc_api_key ).toString('base64'))
    .send({
      'email_address': req.body.email,
      'status': 'subscribed',
      'merge_fields': {
        'FNAME': req.body.firstName,
        'LNAME': req.body.lastName
      }
    })
        .end(function(err, response) {
          if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
            res.send('Signed Up!');
          } else {
            res.send('Sign Up Failed :(');
              }
          });
});

This is where I am trying to fetch in react in my app.js file :

onSubmit = (e,email) => {
  e.preventDefault()
  this.setState({user:email})
  fetch('http://localhost:5000/signup',{
    method: 'POST',
    headers: {
      'Accept':'application/json',
      'Content-type':'application/json'
      },
    body: JSON.stringify({email_address: email, status: 'subscribed'})
  }).then(console.log)
};

when clicking submit I expect the members email address to be sent over to the mailchimp API instead I am getting this error :

Access to fetch at 'http://localhost:5000/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access- Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


回答1:


Try this.

app.use((request, response, next) => {
   response.header("Access-Control-Allow-Origin", "*");
   response.header("Access-Control-Allow-Headers", "Content-Type");
   next();
});

to

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:5000");
  next();
});



回答2:


Just enable CORS on your server.

  1. Install cors
$ npm install --save cors
  1. Enable cors in express:
const cors = require('cors');
const express = require('express');

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

More about cors here.



来源:https://stackoverflow.com/questions/57415145/how-to-send-a-post-request-to-mailchimp-on-express-through-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!