我无法在我的角度应用程序上使用netlify函数创建表单数据的创建请求
我正在尝试将本教程https://www.netlify.com/blog/2018/07/09/building-serverless-crud-apps-with-netlify-functions--faunadb/应用在我的angular7前端项目上。
我的netlify功能:
/* code from functions/todos-create.js */
import faunadb from 'faunadb' /* Import faunaDB sdk */
/* configure faunaDB Client with our secret */
const q = faunadb.query
const client = new faunadb.Client({
secret: process.env.FAUNADB_SECRET
})
/* export our lambda function as named "handler" export */
exports.handler = (event, context, callback) => {
/* parse the string body into a useable JS object */
const data = JSON.parse(event.body)
console.log("Function `todo-create` invoked", data)
const todoItem = {
data: data
}
/* construct the fauna query */
return client.query(q.Create(q.Ref("classes/todos"), todoItem))
.then((response) => {
console.log("success", response)
/* Success! return the response with statusCode 200 */
return callback(null, {
statusCode: 200,
body: JSON.stringify(response)
})
}).catch((error) => {
console.log("error", error)
/* Error! return the error with statusCode 400 */
return callback(null, {
statusCode: 400,
body: JSON.stringify(error)
})
})
}
我的服务:
import { Injectable } from '@angular/core';
import { Mission } from 'src/app/shared/models';
@Injectable({
providedIn: 'root'
})
export class MissionService {
public mission = new Mission();
myTodo = {
title: 'My todo title',
completed: false,
};
constructor() { }
createTodo(data) {
return fetch('/.netlify/functions/todos-create', {
body: JSON.stringify(data),
method: 'POST'
}).then(response => {
return response.json();
});
}
}
按照教程中的要求,我将其添加到package.json的末尾:
"proxy": {
"/.netlify/functions": {
"target": "http://localhost:4200",
"pathRewrite": {
"^/\\.netlify/functions": ""
}
}
}
但我认为应该使用“ http://localhost:4200”的角度地址
我在单击表单按钮时应用了createTodo,但是:
“ ERROR错误:”未捕获(承诺):SyntaxError:JSON.parse: 在Firefox中,JSON数据的第1行第1列出现意外字符”
AND
“来自:: ffff:127.0.0.1的请求:POST / todos-create响应与 12毫秒内状态为500。调用期间发生错误:TypeError:n不是 功能”
答案 0 :(得分:0)
您需要查看netlify函数接收到的事件是什么。看起来主体不是JSON.parse期望的字符串形式的JSON对象。鉴于GET调用没有主体,这不足为奇。