unityWebRequest form post to node.js - c#

I am trying to send login data to server from unity through node.js and node.js will return id of login user. but post does not work. C# Code
form.AddField("usernamePost" , username);
form.AddField("passwordPost" , password);
print(username + " " + inputPassword);
UnityWebRequest www = UnityWebRequest.Post(LoginURL,form);
yield return www.SendWebRequest();
//spinner.Dismiss();
string value= www.downloadHandler.text;
And this is nodejs code
app.use('/ownerLogin', (req,res) =>{
let username=req.query.ownerIdPost;
let userPassword=req.query.passwordPost;
console.log(username);
console.log(userPassword);
I have tried
req.param
req.params
req.body
It gives empty and undefined I also change request method to
app.get('/ownerLogin', (req,res) =>{.....
and
app.post('/ownerLogin', (req,res) =>{....
But nothing worked for me . Kindly help me

It worked on me using
NodeJS:
app.post(`/letlogin`, (req, res) => {
console.log(req.body.username);
});
Unity:
WWWForm formData = new WWWForm () ;
formData.AddField("username", "Barodar");
UnityWebRequest www = UnityWebRequest.Post("http://localhost:3001/letlogin/", formData);
yield return www.SendWebRequest();

Related

How to upload/download a file with Microsoft graph API in Unity3d

I was able to make a oauth 2 login with Unity3d on Microsoft graph, I requested this permission for my app:
https://graph.microsoft.com/files.readwrite.appfolder
After the usual code flow (redirect to url, permission from user, auth code exchanged for token code and token for bearer auth code) I was able to log in.
Problem is that the upload of small files does not work:
https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content
I think this is the best I can do:
string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
using (UnityWebRequest www = UnityWebRequest.Post("https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/createUploadSession", myData)) {
www.SetRequestHeader("Authorization", "Bearer <code>");
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
Debug.Log(www.error + " " + www.downloadHandler.text);
} else {
Debug.Log("Upload complete! " + www.downloadHandler.text);
}
}
and I get this error:
Generic/unknown HTTP error {
"error": {
"code": "BadRequest",
"message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
"innerError": {
"request-id": "id",
"date": "2018-07-20T06:24:30"
}
}
I also tried the WWW class or Put instead of Post but I get "invalid API".
Maybe my problem is in the base url:
https://graph.microsoft.com/v1.0/me
or maybe it's in the path
root:/AppTry/provaupload.json
or maybe in the permission.
I don't really know.
If you know how to make a Rest call with Microsoft Graph and One drive (even not in unity3d and even if you don't know how to solve my specific problem) it would be great to get some example.
To upload file, use the UploadHandler. You must also encode the string as UTF8. As you mentioned in the comment section, it looks like you have to use PUT instead of POST and the url should be changed to something else.
Something more like this:
string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
string url = "https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/content";
using (UnityWebRequest www = new UnityWebRequest(url, "PUT"))
{
byte[] dataToSend = new System.Text.UTF8Encoding().GetBytes(myData);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw(dataToSend);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader("Authorization", "Bearer <code>");
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error + " " + www.downloadHandler.text);
}
else
{
Debug.Log("Upload complete! " + www.downloadHandler.text);
}
}

Exception when downloading Asset Bundle on Android

I'm getting the following exception when I build my game for android
WWW download had an error: java.lang.IllegalArgumentException: uri ==
null
Now I haven o idea why this is happening because it works fine in the editor. Here is the relevant code :
assetLoader.BundleURL = "ftp://user:pass#81.161.248.122/Unity-Uri/AssetBundles/seasonalcontent/christmas";
assetLoader.version = 1;
assetLoader.StartDownload();
and the actual download code :
IEnumerator DownloadAndCache()
{
// Wait for the Caching system to be ready
while (!Caching.ready)
yield return null;
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
{
yield return www;
if (www.error != null)
throw new Exception("WWW download had an error:" + www.error);
AssetBundle bundle = www.assetBundle;
SeasonManager.assets = bundle.LoadAllAssets();
Debug.Log("Stop");
OnContentLoaded();
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
Edit: I got this from the documentation : ftp:// protocol support is limited to anonymous downloads only. Is ftp not supported on android ?
Edit 2: As suggest in the comments I tried this and it results in a Login failed error :
IEnumerator makeRequest()
{
string authorization = authenticate("username", "pass");
string url = "ftp://ipgoeshere";
UnityWebRequest www = UnityWebRequest.Get(url);
www.SetRequestHeader("AUTHORIZATION", authorization);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;
SeasonManager.assets = bundle.LoadAllAssets();
}
}
string authenticate(string username, string password)
{
string auth = username + ":" + password;
auth = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth));
auth = "Basic " + auth;
return auth;
}
To clarify I've made sure that the username password and the server address are correct. I have simply removed them from the code here for obvious reasons.

Unity C#, WWWForm post to Python Flask Server

Hi I am making a game in unity and I need to post information to my python flask server I think that the best method is to use the WWWForms in Unity C# but I can't seem to make it post. Here is my C# Unity Code:
IEnumerator Upload() {
WWWForm form = new WWWForm();
form.AddField("Username", "Stan");
form.AddField("Password", "123456");
using(UnityWebRequest www = UnityWebRequest.Post("http://myserver.com/newuser/", form)) {
yield return www.Send();
if(www.isError) {
Debug.Log(www.error);
}
else {
Debug.Log("Form upload complete!");
}
}
}
It alsways says "From upload complete" and I don't get any errors but when I check my SQL Database it hasn't received the information.
I am pretty sure that my server side code is right because I can post successfully to it through the Form but here is the code anyway:
Python Flask:
class Users(db.Model):
__tablename__ = "userstable"
userid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(4096))
password = db.Column(db.String(4096))
#app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
#app.route("/newuser", methods=["GET", "POST"])
def NewUser():
if request.method == "GET":
return render_template("NewUser.html")
new_user = Users(username=request.form["Username"], password=request.form["Password"])
db.session.add(new_user)
db.session.commit()
return redirect(url_for('NewUser'))
Please Help, and if possible it would be nice to know how to do get requests as well, Thanks!
Stan.

How do I access a database in Unity?

I am trying to POST data to my database in Unity and it doesn't seem to be working. I know it is probably a very stupid mistake as I do have little knowledge in this field.
The C# script I have:
void logIn(string test) {
WWWForm form = new WWWForm();
form.AddField("action","send");
form.AddField("var1",test);
string url = "http://www.prizechief.com/unitycon.php";
WWW w = new WWW(url, form);
}
void Start() {
string sample = "Works";
logIn(sample);
}
My PHP code
<?php
$con = #mysqli_connect("server","un","pass", "db") or die("Could not connect " . mysqli_connect_error() . "Please try again later.");
$var1 = $_GET['var1'];
echo $var1;
mysqli_Query($con,"INSERT INTO test (var) VALUE ('$var1')");
?>
Also, a hint on how to use GET to receive information would be greatly appreciated!
Try this. That should do the WWW request and set $_GET['var1'] = to value1 in your PHP script. Now of course you will have to change that to your variable down the road. But just to test for now. If this doesn't work let me know what the debug logs print out.
void Start () {
string url = "http://www.prizechief.com/unitycon.php?var1=value1";
WWW www = new WWW(url);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
Debug.Log("WWW Ok!: " + www.data);
} else {
Debug.Log("WWW Error: "+ www.error);
}
}
EDIT
Remember to go into Edit > Player Settings > Editor and change the URL to your domain.

Cannot register user on my website (PHP, Unity3D)

I have a website and I want to use it as a place where I can store data (like username, password etc.) for my multiplayer game that I'm making in Unity3D.
Now I want to register someone (add the username and password to the MySQL database) using C# and Unity3D. I use the WWW class to communicate to the website. In my point of view the code I made in Unity3D is working fine, but when I visit phpMyAdmin and search for the new registered user, I can't find it. So I figured, the problem must be in the PHP script, but I can't find it.
Once again the problem is that the username and the password are not added to the MySQL table.
I'll post both scripts, although I think the script in Unity3D is working OK. Please note that I'm PHP absolute beginner.
<?php
$mysql_host = "example.host.com";
$mysql_database = "example_database";
$mysql_user = "exampleuser";
$mysql_password = "toomanysecrets";
try
{
$toQuery = 'SELECT name,
password
FROM basicUserInfo
ORDER BY name';
if ($_POST["name"] || $_POST["password"])
{
$conn = new PDO("mysql:host=$mysql_host;dbname=$mysql_database", $mysql_user, $mysql_password);
echo "Connected to $mysql_database at $mysql_host successfully!";
$forQuery = 'INSERT INTO `a1936371_userinf`.`basicUserInfo` (
`name` ,`password`
)
VALUES (
\'$_POST[\'name\']\', \'$_POST[\'password\']\'
)';
if (!$conn->query($forQuery))
{
echo "Failed to add data!";
}
else
{
echo "Added data sucessfully";
}
//Close the connection
$conn = null;
}
} catch (PDOException $pe)
{
die("Could not connect to the database $mysql_database:" . $pe->getMessage());
}
Unity3D:
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
Register("testt", "test1");
}
}
public void Register(string playername, string password)
{
StartCoroutine(RegisterOnServer(playername, password));
}
IEnumerator RegisterOnServer(string playerName, string password)
{
string url = "http://deathrunserv.net16.net/index.php";
WWWForm form = new WWWForm();
form.AddField("name", playerName);
form.AddField("password", password);
WWW www = new WWW(url);
yield return www;
Debug.Log("Done!");
}
In your C# code, you're not using WWWForm anywhere. Try:
WWWForm form = new WWWForm();
form.AddField("name", playerName);
form.AddField("password", password);
WWW www = new WWW(url, form);
yield return www;
Debug.Log("Done!");

Categories

Resources