我知道这是一个常见的问题,但我已经尝试了相同的问题的解决方案,但无济于事。我只是想使用Webhook从React应用程序向Slack通道发送一条消息,但不知何故,我的输入消息被认为是null/undefined
我的代码:
import React, { useState } from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [message, setMessage] = useState('');
async function submitForm(e) {
e.preventDefault();
const webhookUrl = 'https://hooks.slack.com/services/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';
const data = {
"text": `${message}`,
}
let res = await axios.post(webhookUrl, JSON.stringify(data), {
withCredentials: false,
transformRequest: [(data, headers) => {
delete headers.post["Content-Type"]
return data
}]
})
if (res.status === 200) {
alert("Message Sent!")
//clear state so text boxes clear
setMessage('');
} else {
alert("There was an error. Please try again later.")
}
}
return (
<div className="flex">
<div className="w-1/2 container mx-auto mt-5">
<form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4 self-center">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="message">
Message
</label>
<textarea
className="appearance-none block w-full bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"
id="message"
type="message"
placeholder="Write your message here"
value={message}
onChange={(e) => { setMessage(e.target.value) }}
></textarea>
<button
className="mt-4 shadow bg-purple-500 hover:bg-purple-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded"
onClick={(e) => submitForm(e)}
>
Submit
</button>
</form>
</div>
</div>
);
}
export default App;
以下是错误消息
Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
at axios__WEBPACK_IMPORTED_MODULE_3__.default.post.transformRequest (http://localhost:3000/static/js/bundle.js:41:24)
at transform (http://localhost:3000/static/js/bundle.js:42455:15)
at Object.forEach (http://localhost:3000/static/js/bundle.js:44111:10)
at Object.transformData (http://localhost:3000/static/js/bundle.js:42454:53)
at Axios.dispatchRequest (http://localhost:3000/static/js/bundle.js:42239:75)
at Axios.request (http://localhost:3000/static/js/bundle.js:41683:77)
at Axios.httpMethod [as post] (http://localhost:3000/static/js/bundle.js:41717:19)
at Function.wrap [as post] (http://localhost:3000/static/js/bundle.js:42816:15)
at submitForm (http://localhost:3000/static/js/bundle.js:38:67)
at onClick (http://localhost:3000/static/js/bundle.js:83:25)
我认为问题来自:
JSON.stringify(data)
请帮我一下
1条答案
按热度按时间0md85ypi1#
我认为问题来自于:
headers.post
似乎没有定义。也许您应该直接从headers
访问“Content-Type”?