Last active
May 29, 2022 00:23
-
-
Save jayhuang75/3f82f9c67fa2abc73633d498604f6fc6 to your computer and use it in GitHub Desktop.
nextjs-rust-twitter-stream-websocket-register-fe.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NextJS API - Registeration | |
// folder - pages/api/register.js | |
const RegisterHandler = async (req, res) => { | |
try { | |
let request_url = "http://localhost:8000/register"; | |
// This is a contrived example, normally your external API would exist on another domain. | |
const response = await fetch(request_url, { | |
method: "POST", | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
body: req.body | |
}).catch((error) => { | |
console.error('Error:', error); | |
}); | |
const url_res = await response.json(); | |
console.log(url_res); | |
res.status(response.status || 200).json(url_res); | |
} catch (error) { | |
console.error(error); | |
res.status(error.status || 500).json({ | |
code: error.code, | |
error: error.message | |
}); | |
} | |
} | |
export default RegisterHandler | |
// front end form submittion | |
// folder compoments/register_form.js | |
const [registerErr, setRegisterErr] = useState(false); | |
const handleSubmit = async (e) => { | |
e.preventDefault(); | |
const post_data = { | |
"user_id": v4(), | |
"topic": e.target.topic.value, | |
}; | |
const register_response = await fetch("/api/register", { | |
method: "POST", | |
body: JSON.stringify(post_data) | |
}).catch((error) => { | |
console.error('API Register Error:', error); | |
}); | |
console.log(register_response.status); | |
let ws_res = await register_response.json(); | |
if (register_response.status == 200) { | |
backToMain(ws_res.user_uuid); | |
} else { | |
setRegisterErr(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment