使用Iron-ajax将POST JSON发送到带有节点的SQL Server [英] POST JSON with iron-ajax to SQL Server with Node

查看:90
本文介绍了使用Iron-ajax将POST JSON发送到带有节点的SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Polymer的登录名返回用户数据.我可以在Postman上使用它,但是在将其转换为Polymer时遇到了麻烦.

I am trying to return user data from a login with Polymer. I have it working with Postman, but am having trouble translating it into Polymer.

在Postman中,这将返回JSON对象,但在Polymer中,其将返回undefined.

In Postman this returns a JSON object, but in Polymer it is returning undefined.

聚合物客户端代码[连接到node.js服务器]

Polymer Client Code [Connecting to node.js server]

<iron-ajax id="ajaxUser"
  url="http://localhost:8080/login"
  method="post"
  handle-as="json"
  content-type="application/json"
  headers='{"Access-Control-Allow-Origin": "*"}'
  params="[[params]]"
  on-response="saveUserCredentials"
  last-response="{{user}}"></iron-ajax>

...

<paper-input id="username"></paper-input>
<paper-input id="password"></paper-input>
<paper-button on-tap="loginUser"></paper-button>

...

loginUser() {
  this.params = {"username": this.$.username.value, "password": this.$.password.value};
  console.log(this.params); // logs this.params as populated JSON 
  let request = this.$.ajaxUser.generateRequest();
  request.completes.then(req => {
    console.log(req);       // logs <iron-request></iron-request>
    console.log(this.user); // logs []
  })
  .catch(rejected => {
    console.log(rejected.request); // not returned
    console.log(rejected.error);   // not returned
  })
}

saveUserCredentials() {
  console.log(this.user);
}

节点,Express,mssql服务器代码[连接到SQL Server数据库]

Node, Express, mssql Server Code [Connecting to SQL Server database]

app.post("/login", (req, res) => {
  session.login(req, res)
})

...

exports.login = (req, res) => {
  sql.connect(config.properties)
    .then(pool => {
      pool.request()
        .input('user', sql.VarChar(50), req.body.username)
        .input('password', sql.VarChar(50), req.body.password)
        .query("SELECT role FROM Login WHERE username = @user AND password = @password")
        .then(response => res.send(response))
        .catch(err => res.send(err))
    })
}

错误

SyntaxError:JSON中位置0处的意外令牌#. 在JSON.parse()
在createStrictSyntaxError(C:\ node_modules \ body-parser \ lib \ types \ json.js:157:10) 解析时(C:\ node_modules \ body-parser \ lib \ types \ json.js:83:15)
在C:\ node_modules \ body-parser \ lib \ read.js:121:18. 在invokeCallback(C:\ node_modules \ raw-body \ index.js:224:16)
完成时(C:\ node_modules \ raw-body \ index.js:213:7)
在IncomingMessage.onEnd(C:\ node_modules \ raw-body \ index.js:273:7)
在IncomingMessage.emit(events.js:159:13)
在endReadableNT(_stream_visible.js:1062:12)
在process._tickCallback(internal/process/next_tick.js:152:19)

SyntaxError: Unexpected token # in JSON at position 0 . at JSON.parse ()
at createStrictSyntaxError (C:\node_modules\body-parser\lib\types\json.js:157:10) at parse (C:\node_modules\body-parser\lib\types\json.js:83:15)
at C:\node_modules\body-parser\lib\read.js:121:18 . at invokeCallback (C:\node_modules\raw-body\index.js:224:16)
at done (C:\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:159:13)
at endReadableNT (_stream_readable.js:1062:12)
at process._tickCallback (internal/process/next_tick.js:152:19)

推荐答案

第一个问题似乎是您的服务器在请求中期望使用JSON对象,但是由于缺少根据您的要求标头.要为JSON请求设置Content-Type,请设置 <iron-ajax>.contentType application/json:

The first issue appears to be that your server is expecting a JSON object in the request, but the server sees the request as a string due to a missing Content-Type header on your request. To set the Content-Type for JSON requests, set <iron-ajax>.contentType to application/json:

<iron-ajax content-type="application/json" ...>

好的,我能够通过将content-type = application/json设置为iron-ajax属性来获得服务器响应.现在,由于服务器端错误,在位置0处的JSON中获得了意外令牌#

OK, I was able to get a server response by setting content-type=application/json as an iron-ajax property. Am now getting Unexpected token # in JSON at position 0 as a server side error...

这听起来像是请求实际上不是有效的JSON(因为它包含#作为第一个字符).使用Chrome DevTools网络面板检查有效负载的实际内容.我不会只依赖您代码中的console.log.

That sounds like the request is not actually valid JSON (since it contains a # as the first character). Use the Chrome DevTools Network Panel to inspect the actual contents of the payload. I wouldn't rely solely on console.log in your code.

此外,当我提交时,它现在正在发出两个请求.一种是设置了内容类型的解析为200,另一种是设置为400解析错误.

Also, it is now making two requests when I submit. One with the content-type set, which resolves to 200, and one with that resolves to 400 with parsing error.

第一个消息可能是预检请求,发送到服务器(作为 CORS 的一部分)以检查content-type="application/json"是否为允许的标头.第二条消息是预期的数据请求,但失败,并出现以下错误.

The first message is likely the preflight request, which is sent (as part of CORS) to the server to check whether content-type="application/json" is an allowed header. The second message is the intended data request, but that fails with the following error.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4001' is therefore not allowed access. The response had HTTP status code 400.

您的服务器需要启用CORS请求.有多种方法可以完成此操作,但最简单的Node解决方案可能是使用 cors 包:

Your server needs to enable CORS requests. There are various ways to accomplish this, but the simplest Node solution might be to use the cors package:

const cors = require('cors');
const app = express();
app.use(cors());

这篇关于使用Iron-ajax将POST JSON发送到带有节点的SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆