Добрый день.
Нужны свежие глаза. Не уверен, почему мое обещание возвращает «в ожидании» в консоли браузера:
// contact.js (react)
/* trim */
submitForm = (event) => {
console.log(JSON.stringify(data))
fetch('/contact', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then( (res) => {
res.status === 200 ? this.setState({ submitted: true }) : ''
console.log('submitted: ' + this.state.submitted)
console.log('status:')
console.log(res.json())
})
}
/* trim */
// server.js (node, express)
/* trim */
server.post('/contact', (req, res) => {
const { emailAddress = '', emailName = '', emailMessage = '' } = req.body
console.log(req.body) // outputs correct json obj
let mgData = {
from: emailName + ' <' + emailAddress + '>',
to: mailgun_from_who,
subject: 'From CV Site',
text: emailMessage,
}
const mailgun = require('mailgun-js')({ apiKey: mailgun_api_key, domain: mailgun_domain })
/* These work independently
mailgun.validate(emailAddress, true, function (error, body) {
console.log(body) // correctly outputs on server console the json obj returned from mailgun
}
mailgun.messages().send(mgData, function (error, body) {
console.log(body) // correctly outputs on server console the json obj returned from mailgun
}
*/
/* Now want to promise the validate so if email address does not validate, then
I don't want to send the message, but rather return some message to the contact form
on the browser
Each call to mailgun returns the correct json obj on the server console,
but in the browser's console, the 'status' is 'Promise { <state>: "pending" }'
So, not sure why that's happening in the code below: */
const validateMsg = new Promise( (resolve, reject) => {
mailgun.validate(emailAddress, true, function(error,body) {
if(body) { resolve(body) }
else { reject(Error(error)) }
}
})
// validateMsg.then(successCallback, failureCallback)
validateMsg.then(
function(result) {
console.log('here comes the validate result');
console.log(result); // validate body
res.send(result) // should send validate body back to browser as the promise becomes fulfilled.
}, function(err) {
console.log('here comes the validate result');
console.log(err); // error message
res.send(err) // should send error message back to the browser as the promise
}
)
})
/* trim */
Когда я отправляю форму и смотрю консоли, браузер немедленно выводит данные
как следует перед вызовом fetch (). То же самое верно для консоли сервера,
data obj выводится. Затем оба ждут, пока mailgun обработает запрос проверки.
Как только проверка вернется из почтового пистолета, браузер выдаст:
отправлено: true
состояние:
> Обещание {: "в ожидании"}
И в то же время консоль сервера выводит объект json, возвращенный из почтового пистолета.
Итак, я не уверен, почему json obj, возвращенный из mailgun, не отправляется обратно в браузер.