1

我无法在我的 Angular 应用程序上使用 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,但是:

“错误错误:“未捕获(承诺):SyntaxError:JSON.parse:JSON数据的第1行第1列的意外字符”在Firefox中

“来自 ::ffff:127.0.0.1 的请求:POST /todos-create 响应,状态为 500 在 12 毫秒内。调用期间出错:TypeError:n 不是函数”在控制台中

解决方案在这里:https ://github.com/netlify/netlify-lambda/issues/64

4

1 回答 1

0

您需要查看 netlify 函数接收到的事件是什么。看起来 body 不是 JSON.parse 所期望的字符串形式的 JSON 对象。这并不奇怪,因为 GET 调用没有正文。

于 2019-05-27T13:53:33.330 回答