gpt4 book ai didi

javascript - 如何通过react在express上向mailchimp发送post请求

转载 作者:行者123 更新时间:2023-11-28 10:38:07 26 4
gpt4 key购买 nike

我正在尝试从表单发送新成员(member)资格以对我的 express 服务器使用react,以添加到 mailchimp 成员(member)列表中,但我收到了 cors 错误,并且我不知道是否缺少任何代理。我希望用户能够在 React 中注册,然后将其发送到 mailchimp 数据库

我已经能够获取成员列表,但不允许我向其中发帖:

这是我的 Express 后端:

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 :(');
}
});
});

这是我尝试在 app.js 文件中获取 React 的位置:

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)
};

当点击提交时,我希望将成员(member)电子邮件地址发送到 mailchimp API,但我收到此错误:

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.

最佳答案

试试这个。

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

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

关于javascript - 如何通过react在express上向mailchimp发送post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57415145/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com