gpt4 book ai didi

javascript - ReactJS 中的错误 "Assignment to constant variable"

转载 作者:行者123 更新时间:2023-12-05 03:52:47 25 4
gpt4 key购买 nike

我确实遵循了如何将 mailchimp 与节点后端集成的教程。我从来没有接触过后端,所以我对此很蹩脚。当我发布到他们的 API 时,我得到了订阅者的凭据,但我得到了一个错误 - “分配给常量变量”。阅读网络和其他 SO 问题,似乎我正在尝试重新分配一个 CONST 值。

我仔细看了看我的代码,我唯一注意到这里可能有问题的是

request(options, (error, response, body) => {


try {
const resObj = {};
if (response.statusCode == 200) {
resObj = {
success: `Subscibed using ${email}`,
message: JSON.parse(response.body),
};
} else {
resObj = {
error: ` Error trying to subscribe ${email}. Please, try again`,
message: JSON.parse(response.body),
};
}
res.send(respObj);
} catch (err) {
const respErrorObj = {
error: " There was an error with your request",
message: err.message,
};
res.send(respErrorObj);
}
});

我注意到我正在创建一个名为 "resObj" 的空对象,然后尝试为其分配一个值。我已尝试将 CONST 更改为 LET,但我收到一条错误消息:"resObj is not defined"

这是我的前端代码:

 import React, { useState } from "react";
import "./App.css";
import Subscribe from "./components/Subscribe";
import Loading from "./components/Loading/Loading";
import axios from "axios";
import apiUrl from "./helpers/apiUrl";

function App() {
const [loading, setLoading] = useState(false);
const [email, setEmail] = useState("");

const handleSendEmail = (e) => {
setLoading(true);
console.log(email);
axios
.post(`${apiUrl}/subscribe`, { email: email })
.then((res) => {
if (res.data.success) {
alert(`You have successfully subscribed!, ${res.data.success}`);
setEmail("");
setLoading(false);
} else {
alert(`Unable to subscribe, ${res.data.error}`);
console.log(res);
setLoading(false);
setEmail("");
}
})
.catch((err) => {
setLoading(false);
alert("Oops, something went wrong...");
console.log(err);
setEmail("");
});
e.preventDefault();
};

const handleInput = (event) => {
setEmail(event.target.value);
};

// const handleLoadingState = (isLoading) => {
// setLoading({ isLoading: loading });
// console.log(loading);
// };
return (
<div className='App'>
<h1>Subscribe for offers and discounts</h1>

{loading ? (
<Loading message='Working on it...' />
) : (
<Subscribe
buttonText='Subscribe'
value={email}
handleOnChange={handleInput}
handleOnSubmit={handleSendEmail}
/>
)}
</div>
);
}

export default App;

后端代码:

const restify = require("restify");
const server = restify.createServer();
const corsMiddleware = require("restify-cors-middleware");
const request = require("request");
require("dotenv").config({ path: __dirname + "/variables.env" });

const subscribe = (req, res, next) => {
const email = req.body.email;
const dataCenter = process.env.DATA_CENTER;
const apiKey = process.env.MAILCHIMP_API_KEY;
const listID = process.env.LIST_ID;

const options = {
url: `https://${dataCenter}.api.mailchimp.com/3.0/lists/${listID}/members`,
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `apikey ${apiKey}`,
},
body: JSON.stringify({ email_address: email, status: "subscribed" }),
};

request(options, (error, response, body) => {
try {
const resObj = {};
if (response.statusCode == 200) {
resObj = {
success: `Subscibed using ${email}`,
message: JSON.parse(response.body),
};
} else {
resObj = {
error: ` Error trying to subscribe ${email}. Please, try again`,
message: JSON.parse(response.body),
};
}
res.send(respObj);
} catch (err) {
const respErrorObj = {
error: " There was an error with your request",
message: err.message,
};
res.send(respErrorObj);
}
});
next();
};

const cors = corsMiddleware({
origins: ["http://localhost:3001"],
});

server.pre(cors.preflight);
server.use(restify.plugins.bodyParser());
server.use(cors.actual);
server.post("/subscribe", subscribe);

server.listen(8080, () => {
console.log("%s listening at %s", server.name, server.url);
});

如果有人能提供帮助,我将不胜感激。订阅表单有效,但我需要清除该错误,以便我的前端在提交表单时正常工作。

最佳答案

也许您正在寻找的是 Object.assign(resObj, { whatyouwant: value} )

这样您就不会重新分配 resObj 引用(由于 resObj 是常量,因此无法重新分配),而只是更改其属性。

Reference at MDN website

编辑:此外,您应该编写 res.send(resObj) 而不是 res.send(respObj),这只是一个错字

关于javascript - ReactJS 中的错误 "Assignment to constant variable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62053637/

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