이제 NodeBird 앱의 코드를 수정해 NodeBird에서 클라우드 펑션스 서비스를 이용할 수 있게 해봅시다.
nodebird/controllers/post.js
const { Post, Hashtag } = require('../models');
exports.afterUploadImage = (req, res) => {
console.log(req.file);
const filePath = req.file.path.split('/').splice(0, 3).join('/');
const originalUrl = `${filePath}/${req.file.filename}`;
const url = originalUrl.replace(/\/original\//, '/thumb/');
res.json({ url, originalUrl });
};
...
nodebird/views/main.html
...
{٪ for twit in twits ٪}
<div class="twit">
<input type="hidden" value="{{twit.User.id}}" class="twit-user-id">
<input type="hidden" value="{{twit.id}}" class="twit-id">
<div class="twit-author">{{twit.User.nick}}</div>
{٪ if not followingIdList.includes(twit.User.id) and twit.User.id !== user.id ٪}
<button class="twit-follow">팔로우하기</button>
{٪ endif ٪}
<div class="twit-content">{{twit.content}}</div>
{٪ if twit.img ٪}
<div class="twit-img">
<img
src="{{twit.img}}"
onerror="this.src = this.src.replace(/\/thumb\//, '/original/');"
alt="섬네일"
/>
</div>
{٪ endif ٪}
</div>
{٪ endfor ٪}
</div>
</div>
{% endblock %}
{% block script %}
<script>
if (document.getElementById('img')) {
document.getElementById('img').addEventListener('change', function(e) {
const formData = new FormData();
console.log(this, this.files);
formData.append('img', this.files[0]);
axios.post('/post/img', formData)
.then((res) => {
document.getElementById('img-url').value = res.data.url;
document.getElementById('img-preview').src = res.data.originalUrl;
document.getElementById('img-preview').style.display = 'inline';
})
.catch((err) => {
console.error(err);
});
});
}
...